Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Unity 自定義日志系統:屏幕輸出與 Key 過濾

編輯:關於 Android 程式設計

開發中我們常覺得 Unity 自帶的日志系統不夠好用:不能按條件篩選、不能打印到屏幕上、也不能生成自定義日志文件。這就需要擴展編輯器的相關功能。本文實現的需求比較簡單:給日志加一個 key,可按 key 過濾暫時不需要顯示的日志,並把日志打印到屏幕上。

屏幕打印部分參考了一份開源的 DebugConsole.cs,但原版本較早且存在錯誤與冗餘,感興趣可自行搜索。順帶一提,老外特別喜歡用 while 循環,很多能用 for 的地方也寫成 while,大概是為了少打字吧。

效果如下:

這樣用:

或者這樣用:

整個系統由兩個類組成:一個負責控制台打印,一個負責屏幕打印。

DebugMgr:日志管理器

namespace GameFramework {
    /// <summary>
    /// 日志管理器
    /// </summary>
    public class DebugMgr {
        // 日志基類
        protected abstract class LogDataBase {
            public string key;
            public string log;

            public LogDataBase(string _key, string _log) {
                key = _key;
                log = _log;
            }

            protected string GetLog(string format) {
                return string.Format(format, key, log);
            }

            public abstract string Print(string format);
        }

        protected class LogData : LogDataBase {
            public LogData(string key, string message) : base(key, message) { }
            public override string Print(string format) {
                string logTxt = base.GetLog(format);
                Debug.Log(logTxt);
                return logTxt;
            }
        }

        protected class LogWarningData : LogDataBase {
            public LogWarningData(string key, string message) : base(key, message) { }
            public override string Print(string format) {
                string logTxt = base.GetLog(format);
                Debug.LogWarning(logTxt);
                return logTxt;
            }
        }

        protected class LogErrorData : LogDataBase {
            public LogErrorData(string key, string message) : base(key, message) { }
            public override string Print(string format) {
                string logTxt = base.GetLog(format);
                Debug.LogError(logTxt);
                return logTxt;
            }
        }

        // 日志格式
        public static string format = "{0}:{1}";
        // 是否屏幕顯示
        public static bool screenDisplay = false;

        // 過濾 key 集合
        private static List<string> s_filterKeyList = new List<string>();

        public static void ClearFilterKey() {
            s_filterKeyList.Clear();
        }

        public static void AddFilterKey(string key) {
            if (s_filterKeyList.Contains(key)) return;
            s_filterKeyList.Add(key);
        }

        public static void RemoveFilterKey(string key) {
            if (s_filterKeyList.Contains(key)) s_filterKeyList.Remove(key);
        }

        private static string Print(LogDataBase ld) {
            if (ld == null) return "";
            // key 被過濾則不打印
            if (s_filterKeyList.Contains(ld.key)) return "";
            return ld.Print(format);
        }

        public static void Log(string log, string key = "日志") {
            string logTxt = DebugMgr.Print(new LogData(key, log));
            if (screenDisplay) DebugConsole.Log(logTxt);
            else DebugConsole.Clear();
        }

        public static void LogWarning(string log, string key = "警告") {
            string logTxt = DebugMgr.Print(new LogWarningData(key, log));
            if (screenDisplay) DebugConsole.LogWarning(logTxt);
            else DebugConsole.Clear();
        }

        public static void LogError(string log, string key = "錯誤") {
            string logTxt = DebugMgr.Print(new LogErrorData(key, log));
            if (screenDisplay) DebugConsole.LogError(logTxt);
            else DebugConsole.Clear();
        }
    }
}

DebugConsole:屏幕打印

namespace GameFramework {
    public class DebugConsole : MonoBehaviour {
        public enum LogColor { NORMAL, WARNING, ERROR }

        public Color normalColor = Color.green;
        public Color warningColor = Color.yellow;
        public Color errorColor = Color.red;
        public GameObject debugGui = null;
        public Vector3 defaultGuiPosition = new Vector3(0.01f, 0.98f, 0f);
        public int maxLogs = 30;
        public float lineSpacing = 0.03f;
        public bool draggable = true;
        public bool visible = true;

        private List<GUIText> m_guiList = new List<GUIText>();
        private List<string> m_logList = new List<string>();
        private List<LogColor> m_colorList = new List<LogColor>();

        private static DebugConsole s_instance = null;

        public static DebugConsole GetInstance() {
            if (s_instance == null) {
                s_instance = (DebugConsole) FindObjectOfType(typeof(DebugConsole));
                if (s_instance == null) {
                    GameObject console = new GameObject();
                    console.name = "DebugConsole";
                    console.AddComponent<DebugConsole>();
                    s_instance = (DebugConsole) FindObjectOfType(typeof(DebugConsole));
                }
            }
            return s_instance;
        }

        void Awake() {
            DontDestroyOnLoad(this);
            s_instance = this;
            this.InitGuis();
        }

        // 加日志
        private void AddLog(string log, LogColor color = LogColor.NORMAL) {
            m_logList.Add(log);
            m_colorList.Add(color);
            this.Display();
        }

        // 清日志
        private void ClearLog() {
            m_logList.Clear();
            m_colorList.Clear();
            this.ClearScreen();
        }

        public static void Log(string log) {
            DebugConsole.GetInstance().AddLog(log, LogColor.NORMAL);
        }

        public static void LogWarning(string log) {
            DebugConsole.GetInstance().AddLog(log, LogColor.WARNING);
        }

        public static void LogError(string log) {
            DebugConsole.GetInstance().AddLog(log, LogColor.ERROR);
        }

        public static void Clear() {
            DebugConsole.GetInstance().ClearLog();
        }
    }
}

測試類

public class Test : MonoBehaviour {
    public bool screenDisplay = false;

    void Start() {
        DebugMgr.Log("開始了");
    }

    private int m_count = 0;

    void OnGUI() {
        if (GUI.Button(new Rect(500, 0, 100, 100), "加log")) {
            DebugMgr.screenDisplay = screenDisplay;
            string log = "count = " + m_count;
            DebugMgr.Log(log);
            DebugMgr.LogWarning(log);
            DebugMgr.LogError(log);
            ++m_count;
        }
    }
}

友情提示:你可能發現左鍵點擊 Console 窗口下的日志時,系統會跳轉到 DebugMgr 類,而不是真正打日志的地方。解決方法很簡單:把這兩個類封裝成獨立的 C# 類庫項目,生成 dll 後再導入項目,這樣 Unity 追蹤堆棧調用時就會指向真正打日志的位置了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved