天天看點

Unity用GUI繪制Debug/print視窗/控制台-打包後測試12支援

Unity遊戲視窗控制台輸出

本文提供全流程,中文翻譯。

Chinar 堅持将簡單的生活方式,帶給世人!

(擁有更好的閱讀體驗 —— 高分辨率使用者請根據需求調整網頁縮放比例)

Chinar —— 心分享、心創新!

助力快速在 Game 視窗用 GUI 實作一個控制台的輸出面闆

為新手節省寶貴的時間,避免采坑!

Chinar 教程效果:(可打包後執行-便于調試)

全文高清圖檔,點選即可放大觀看 (很多人竟然不知道)

将該腳本挂載空物體上,無需其他任何配置

運作 / 打包後,按下按鍵 Q 即可打開 / 關閉面闆

提示:

(可通過 Inspector 面闆 ShortcutKey 屬性自定義打開控制台面闆的快捷鍵)

#define MACRO_CHINAR
using System.Collections.Generic;
using UnityEngine;



namespace ChinarConsole
{
    /// <summary>
    /// Chinar可視控制台
    /// </summary>
    class ChinarViewConsole : MonoBehaviour
    {
#if MACRO_CHINAR
        struct Log
        {
            public string  Message;
            public string  StackTrace;
            public LogType LogType;
        }


        #region Inspector 面闆屬性

        [Tooltip("快捷鍵-開/關控制台")]  public KeyCode ShortcutKey       = KeyCode.Q;
        [Tooltip("搖動開啟控制台?")]    public bool    ShakeToOpen       = true;
        [Tooltip("視窗打開加速度")]     public float   shakeAcceleration = 3f;
        [Tooltip("是否保持一定數量的日志")] public bool    restrictLogCount  = false;
        [Tooltip("最大日志數")]       public int     maxLogs           = 1000;

        #endregion

        private readonly List<Log> logs = new List<Log>();
        private          Log       log;
        private          Vector2   scrollPosition;
        private          bool      visible;
        public           bool      collapse;

        static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
        {
            {LogType.Assert, Color.white},
            {LogType.Error, Color.red},
            {LogType.Exception, Color.red},
            {LogType.Log, Color.white},
            {LogType.Warning, Color.yellow},
        };

        private const string     ChinarWindowTitle = "Chinar-控制台";
        private const int        Edge              = 20;
        readonly      GUIContent clearLabel        = new GUIContent("清空", "清空控制台内容");
        readonly      GUIContent hiddenLabel       = new GUIContent("合并資訊", "隐藏重複資訊");

        readonly Rect titleBarRect = new Rect(0, 0, 10000, 20);
        Rect          windowRect   = new Rect(Edge, Edge, Screen.width - (Edge * 2), Screen.height - (Edge * 2));


        void OnEnable()
        {
#if UNITY_4
            Application.RegisterLogCallback(HandleLog);
#else
            Application.logMessageReceived += HandleLog;
#endif
        }


        void OnDisable()
        {
#if UNITY_4
            Application.RegisterLogCallback(null);
#else
            Application.logMessageReceived -= HandleLog;
#endif
        }


        void Update()
        {
            if (Input.GetKeyDown(ShortcutKey)) visible                                      = !visible;
            if (ShakeToOpen && Input.acceleration.sqrMagnitude > shakeAcceleration) visible = true;
        }


        void OnGUI()
        {
            if (!visible) return;
            windowRect = GUILayout.Window(666, windowRect, DrawConsoleWindow, ChinarWindowTitle);
        }


        void DrawConsoleWindow(int windowid)
        {
            DrawLogsList();
            DrawToolbar();
            GUI.DragWindow(titleBarRect);
        }


        void DrawLogsList()
        {
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            for (var i = 0; i < logs.Count; i++)                        
            {
                if (collapse && i > 0) if (logs[i].Message != logs[i - 1].Message) continue; 
                GUI.contentColor = logTypeColors[logs[i].LogType];
                GUILayout.Label(logs[i].Message);
            }
            GUILayout.EndScrollView();     
            GUI.contentColor = Color.white; 
        }


        void DrawToolbar()
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button(clearLabel))
            {
                logs.Clear();
            }

            collapse = GUILayout.Toggle(collapse, hiddenLabel, GUILayout.ExpandWidth(false));
            GUILayout.EndHorizontal();
        }


        void HandleLog(string message, string stackTrace, LogType type)
        {
            logs.Add(new Log
            {
                Message    = message,
                StackTrace = stackTrace,
                LogType    = type,
            });
            DeleteExcessLogs();
        }


        void DeleteExcessLogs()
        {
            if (!restrictLogCount) return;
            var amountToRemove = Mathf.Max(logs.Count - maxLogs, 0);
            print(amountToRemove);
            if (amountToRemove == 0)
            {
                return;
            }

            logs.RemoveRange(0, amountToRemove);
        }
#endif
    }
}           

當你的項目中有列印輸出的時候,面闆上會直接顯示資訊

效果類似于 Unity 的 Console 視窗

void Update()
        {
            print("Chinar-Console");
            Debug.Log("Debug.Log");
        }           

擁有自己的伺服器,無需再找攻略!

Chinar 提供一站式教程,閉眼式建立!

為新手節省寶貴時間,避免采坑!

先點選領取 —— 阿裡全産品優惠券 (享受最低優惠)

1 ——

雲伺服器超全購買流程 (新手必備!)

2 ——

阿裡ECS雲伺服器自定義配置 - 購買教程(新手必備!)

3——

Windows 伺服器配置、運作、建站一條龍 !

4 ——

Linux 伺服器配置、運作、建站一條龍 !

技術交流群:806091680 ! Chinar 歡迎你的加入

END

本部落格為非營利性個人原創,除部分有明确署名的作品外,所刊登的所有作品的著作權均為本人所擁有,本人保留所有法定權利。違者必究

對于需要複制、轉載、連結和傳播部落格文章或内容的,請及時和本部落客進行聯系,留言,Email: [email protected]

對于經本部落客明确授權和許可使用文章及内容的,使用時請注明文章或内容出處并注明網址

繼續閱讀