[Unity] 實作具選擇性開關的 Debug Logger
Overview
本篇旨在說明如何撰寫自訂的 Debug Logger,並有以下功能:
1. 可以完全開關 Log
2. 可以選擇性開關 Log
3. 雙擊可以跳至 Log Stack 最外層
4. 調整大小、粗細、顏色等顯示優化
在程式開發階段肯定是需要 Debug 的
Debug 方式除了下中斷點外就是下 Log
Unity 所提供的 Debug.Log 雖然好用
但主要有以下兩點問題
1. 效能不佳
2. 沒有一個好的開關
因此為了解決以上問題
通常我們會自己寫一個開關
在 Release 時把 Log 關閉
private bool m_isDebug = false; private void DebugLog( string log ) { if ( m_isDebug ) { Debug.Log( log ); } }
但這樣會造成另外一個令人不爽的問題
每次雙擊都會跑到這個函式下
還得要看 Stack 追回去
十分沒有效率
要解決這個問題剪刀找到兩個解法
解法一:利用 Scripting Define Symbol
缺點一:調整參數後會需要重編
缺點二:還是沒解決選擇性 Log 的問題
此方法只要用 RELEASE Define 重新封裝 Debug Class
然後 Function 全部都不實作即可
#if RELEASE using UnityEngine; public static class Debug { public static void Log( object message ) { } public static void Log( object message, UnityEngine.Object context ) { } public static void LogError( object message ) { } public static void LogError( object message, UnityEngine.Object context ) { } public static void LogException( System.Exception exception ) { } public static void LogException( System.Exception exception, UnityEngine.Object context ) { } public static void LogWarning( object message ) { } public static void LogWarning( object message, UnityEngine.Object context ) { } } #endif
這個做法在要出版本時
在 Build Settings 的 Scripting Define Symbol 欄位
加入 RELEASE Define 即可
解法二:重新封裝一個 Debug Class,並包成 Dll
此方法算是可以一勞永逸
雖然要重寫原本 Unity Debug 類別的函式
但可以加入自定義的特殊 Log
另外為了選擇性 Log 的功能
這邊使用了一 Dictionary 來儲存需要 Log 的 object
透過開關,還是可以直接關閉所有 Log
詳細實作與使用方法請參考 Github:
Debug.cs - Github
Hotter - Github
如何打包成 Dll 請參考以下這篇文章:
[Unity] 如何建立 Dll?
UnityEngine.Debug.Log( "UnityEngine.Debug.Log" ); Debug.Log( "Log" ); Debug.LogError( "LogError" ); Debug.LogWarning( "LogWarning" ); Debug.LogBold( "LogBold" ); Debug.LogItalic( "LogItalic" ); Debug.LogColor( "LogRed", "red" ); Debug.LogColor( "LogYellow", "yellow" ); Debug.LogColor( "LogGreen", "green" ); Debug.FontSize = 14; Debug.Log( "FontSize: " + Debug.FontSize ); // Filter Debug.Log( this, "Before adding" ); Debug.Add( this ); Debug.Log( this, "Filter Log" ); Debug.LogWarning( this, "Filter LogWarning" ); Debug.LogError( this, "Filter LogError" ); Debug.Remove( this ); Debug.Log( this, "After removing" );
Debug.Log 的顯示二三事
1. Log 多一行 UnityEngine.Debug:Log(Object):透過加入換行 ("\n") 解決
2. 更改字型大小:加入 size 標籤
3. 粗體:加入 b 標籤
4. 斜體:加入 i 標籤
5. 顏色:加入 color 標籤
歡迎您留言與分享!(Welcome for comments or sharing!)
- [Unity] Admob 使用教學 (Android + iOS)
- [Unity] 如何建立 Dll?