栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

Unity3D在Preview中打印日志的方法

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity3D在Preview中打印日志的方法

Preview窗口除了可以预览模型之外,我们还可以做别的操作。

今天我们来写个小工具在Preview窗口中显示调试信息。

可以看下面的图,同样是打印 health 和 power 的日志,在 Preview 中显示比在 Console 中显示舒服多了。

左边是Console中显示,右边是Preview窗口中显示。

创建Editor目录,然后把下面的脚本放进去

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Object), true)]
public class PreviewGUIEditor : Editor {
 
 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;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/122409.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号