Unity3D在Preview中打印日志的方法
- 作者: 长劲鹿哟
- 来源: 51数据库
- 2020-08-11
这篇文章主要为大家详细介绍了Unity3D在Preview中打印日志的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
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;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
