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;
	}
}

更多Unity开发教程,请关注微信公众号UnityAsk。 QQ技术交流群 891920228

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值