Unity3D在Preview中打印日志的方法
程序员文章站
2023-11-14 18:51:05
preview窗口除了可以预览模型之外,我们还可以做别的操作。
今天我们来写个小工具在preview窗口中显示调试信息。
可以看下面的图,同样是打印 health 和 po...
preview窗口除了可以预览模型之外,我们还可以做别的操作。
今天我们来写个小工具在preview窗口中显示调试信息。
可以看下面的图,同样是打印 health 和 power 的日志,在 preview 中显示比在 console 中显示舒服多了。
左边是console中显示,右边是preview窗口中显示。
创建editor目录,然后把下面的脚本放进去
using unityengine; using unityeditor; [customeditor(typeof(object), true)] public class previewguieditor : editor { /** update every 15th frame. */ private const int updateonframe = 15; private guistyle _previewlabelstyle; private guistyle previewlabelstyle { get { if (_previewlabelstyle == null) { _previewlabelstyle = new guistyle("preoverlaylabel") { richtext = false, alignment = textanchor.upperleft, fontstyle = fontstyle.normal }; // try to get a fixed-width font on macos. var font = font.createdynamicfontfromosfont("monaco", 12); // failing that, try to get a fixed-width font on windows. if (font == null) font = font.createdynamicfontfromosfont("lucida console", 12); // xxx what fixed-width font should i request if we're on linux? if (font != null) _previewlabelstyle.font = font; // debug.log("fonts: \n" + string.join("\n", font.getosinstalledfontnames())); } return _previewlabelstyle; } } public override bool haspreviewgui() { return application.isplaying; } public override bool requiresconstantrepaint() { // only repaint on the nth frame. return application.isplaying && time.framecount % updateonframe == 0; } public override void onpreviewgui(rect rect, guistyle background) { string str = target.tostring(); gui.label(rect, str, previewlabelstyle); } }
在我们需要打印日志的类里面 重载tostring()函数,返回需要在preview中输出的内容。
下面是上面截图的示例,一个player类,在tostring()函数中返回了 health 和 power的输出内容。
using unityengine; public class player : monobehaviour { public int health = 10; public int power = 10; // use this for initialization void start () { } // update is called once per frame void update () { health += 1; power += 2; debug.logerror("health = "+ health); debug.logerror("power = "+ power); } public override string tostring() { return "health = " + health+"\n"+ "power = " + power; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。