Unity3D在Preview中打印日志的方法
Preview窗口除了可以預(yù)覽模型之外,我們還可以做別的操作。
今天我們來寫個(gè)小工具在Preview窗口中顯示調(diào)試信息。
可以看下面的圖,同樣是打印 health 和 power 的日志,在 Preview 中顯示比在 Console 中顯示舒服多了。
左邊是Console中顯示,右邊是Preview窗口中顯示。
創(chuàng)建Editor目錄,然后把下面的腳本放進(jìn)去
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()函數(shù),返回需要在preview中輸出的內(nèi)容。
下面是上面截圖的示例,一個(gè)Player類,在ToString()函數(shù)中返回了 health 和 power的輸出內(nèi)容。
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; } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c#求點(diǎn)到直線的投影點(diǎn)坐標(biāo)
這篇文章主要介紹了c#求直線外一點(diǎn)到該直線的投影點(diǎn),大家參考使用吧2013-12-12探討:關(guān)閉瀏覽器后,php腳本會(huì)不會(huì)繼續(xù)運(yùn)行
本篇文章是對(duì)關(guān)閉瀏覽器后,php腳本會(huì)不會(huì)繼續(xù)運(yùn)行進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06基于c#圖像灰度化、灰度反轉(zhuǎn)、二值化的實(shí)現(xiàn)方法詳解
本篇文章是對(duì)c#圖像灰度化、灰度反轉(zhuǎn)、二值化的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#實(shí)現(xiàn)定時(shí)任務(wù)Task Scheduler的示例代碼
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)定時(shí)任務(wù)Task Scheduler的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02WinForm實(shí)現(xiàn)按名稱遞歸查找控件的方法
這篇文章主要介紹了WinForm實(shí)現(xiàn)按名稱遞歸查找控件的方法,需要的朋友可以參考下2014-08-08