Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> unity 日志系統

unity 日志系統

編輯:關於Android編程

我們在開發中,往往會覺得unity自帶的日志系統不是那麼好用,比如,不能篩選日志,不能打印在屏幕上,想生成自己的日志文件,等等等等的需求,這時候就需要自己來擴展編輯器的相關功能了。我這裡實現的需求比較簡單,就是給日志加了個key,可以根據這個key來對暫時不需要顯示的日志進行過濾,還有就是將我們的日志打印到屏幕上去。

打印屏幕的類參考了由 Jeremy Hollingsworth 和 Simon Waite 這2人寫的一個 DebugConsole.cs 類,不過他們2個的版本實在是太早了,而且還有錯誤和啰嗦的地方,有興趣的話你可以去搜來看看。外加老外真的很喜歡用while循環呀,好多能用for的地方也是while,是因為這樣寫字比較少嗎?看來大家都是懶癌晚期患者,(:зゝ∠)

一直犯懶,終於把它給寫了。。。有時間我也給它扔到 github 上去。。。
外加如果想要輸出日志文件,或者其它什麼功能的,你就自己加就好了,我當前的需求還是挺簡單的~

效果如圖:

這樣用
這裡寫圖片描述

或者這樣用
這裡寫圖片描述

一共由2個類組成,一個負責控制台打印,一個負責屏幕打印<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text; namespace GameFramework { ///

/// 日志管理器 /// public class DebugMgr { #region 日志結構 /// /// 日志基類 /// protected abstract class LogDataBase { /// /// key /// public string key; /// /// 日志 /// public string log; /// /// 構造 /// ///key ///日志 public LogDataBase(string _key, string _log) { key = _key; log = _log; } /// /// 獲取log /// ///格式 /// log protected string GetLog(string format) { string txt = string.Format(format, key, log); return txt; } /// /// 打印 /// ///格式 /// 日志 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; } } #endregion 日志結構類 ------------------------------------ /// /// 日志格式 /// public static string format = "{0}:{1}"; /// /// 屏幕顯示 /// public static bool screenDisplay = false; // 過濾key集合 private static List s_filterKeyList = new List(); /// /// 清除所有key /// public static void ClearFilterKey() { s_filterKeyList.Clear(); } /// /// 增加key /// ///key public static void AddFilterKey(string key) { // 不加重復的key if (s_filterKeyList.Contains(key)) return; s_filterKeyList.Add(key); } /// /// 移除key /// ///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 ""; // 打印日志 string logTxt = ld.Print(format); return logTxt; } /// /// 日志 /// ///日志 ///key public static void Log(string log, string key = "日志") { LogData ld = new LogData(key, log); string logTxt = DebugMgr.Print(ld); if (screenDisplay) DebugConsole.Log(logTxt); else DebugConsole.Clear(); } /// /// 警告 /// ///日志 ///key public static void LogWarning(string log, string key = "警告") { LogWarningData ld = new LogWarningData(key, log); string logTxt = DebugMgr.Print(ld); if (screenDisplay) DebugConsole.LogWarning(logTxt); else DebugConsole.Clear(); } /// /// 錯誤 /// ///日志 ///key public static void LogError(string log, string key = "錯誤") { LogErrorData ld = new LogErrorData(key, log); string logTxt = DebugMgr.Print(ld); if (screenDisplay) DebugConsole.LogError(logTxt); else DebugConsole.Clear(); } } }
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

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;

        /// 
        /// 第一個gui組件
        /// 
        public GameObject debugGui = null;
        /// 
        /// 默認gui位置
        /// 
        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 m_guiList = new List();
        private List m_logList = new List();
        private List m_colorList = new List();


        // 單例
        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();

                    s_instance = (DebugConsole)FindObjectOfType(typeof(DebugConsole));
                }
            }

            return s_instance;
        }

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

        private void InitGuis()
        {
            // 初始化第一個gui
            if (debugGui == null)
            {
                debugGui = new GameObject();
                debugGui.name = "DebugGUI(0)";
                debugGui.transform.SetParent(this.transform, false);
                debugGui.transform.position = defaultGuiPosition;

                GUIText gt = debugGui.AddComponent();
                m_guiList.Add(gt);
            }

            // 創建其它的gui
            Vector3 position = debugGui.transform.position;
            int guiCount = 1;
            while (guiCount < maxLogs)
            {
                position.y -= lineSpacing;

                GameObject clone = (GameObject)Instantiate(debugGui, position, transform.rotation);
                clone.name = string.Format("DebugGUI({0})", guiCount);
                GUIText gt = clone.GetComponent();
                m_guiList.Add(gt);

                position = clone.transform.position;

                ++guiCount;
            }
            // 設置父節點
            guiCount = 0;
            while (guiCount < m_guiList.Count)
            {
                GUIText temp = (GUIText)m_guiList[guiCount];
                temp.transform.parent = debugGui.transform;

                ++guiCount;
            }
        }


        // 連接到手指
        private bool connectedToMouse = false;
        void Update()
        {
            // 拖拽移動
            if (draggable)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    if (connectedToMouse)
                    {
                        connectedToMouse = false;
                    }
                    else if (connectedToMouse == false && debugGui.GetComponent().HitTest((Vector3)Input.mousePosition))
                    {
                        connectedToMouse = true;
                    }
                }

                if (connectedToMouse)
                {
                    float posX = Input.mousePosition.x / Screen.width;
                    float posY = Input.mousePosition.y / Screen.height;
                    debugGui.transform.position = new Vector3(posX, posY, 0F);
                }
            }
        }


        /// 
        /// 清屏
        /// 
        private void ClearScreen()
        {
            // 對象還沒創建全的情況下不清
            if (m_guiList.Count < maxLogs)
                return;

            int count = 0;
            while (count < m_guiList.Count)
            {
                GUIText gt = m_guiList[count];
                gt.text = "";

                ++count;
            }
        }

        /// 
        /// 精簡多出來的消息
        /// 
        private void Prune()
        {
            if (m_logList.Count <= maxLogs)
                return;

            int diff = m_logList.Count - maxLogs;

            m_logList.RemoveRange(0, diff);
            m_colorList.RemoveRange(0, diff);
        }

        /// 
        /// 顯示
        /// 
        private void Display()
        {
            if (visible)
            {
                // 先嘗試是否能精簡
                this.Prune();

                // gui不夠
                if (m_guiList.Count < maxLogs)
                    return;

                // 顯示
                int guiCount = 0;
                while (guiCount < m_guiList.Count && guiCount < m_logList.Count)
                {
                    GUIText gt = m_guiList[guiCount];

                    // 文本
                    gt.text = m_logList[guiCount];

                    // 顏色
                    LogColor lc = m_colorList[guiCount];
                    switch (lc)
                    {
                        case LogColor.NORMAL:
                            {
                                gt.material.color = this.normalColor;
                            }
                            break;
                        case LogColor.WARNING:
                            {
                                gt.material.color = this.warningColor;
                            }
                            break;
                        case LogColor.ERROR:
                            {
                                gt.material.color = this.errorColor;
                            }
                            break;
                    }

                    // 循環
                    ++guiCount;
                }
            }
            else
            {
                // 清屏
                this.ClearScreen();
            }
        }

        // 加日志
        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();
        }
    }
}

測試類:

using UnityEngine;
using System.Collections;

using GameFramework;

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

    // Use this for initialization
    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 類裡,而不是真正打日志的地方,想要解決這個問題也很簡單。你就把這2個類編譯封裝成一個單獨的c#類庫項目,生成dll後,再導入項目中就可以了,這樣 unity 在追蹤程序的堆棧調用時,跳轉的位置就會指向你真正打日志的地方了,輕松又愉快~

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved