[Unity 程式] Debug.Log 列印紀錄

2021.02.10 / Unity 引擎

Debug.Log 用於列印腳本執行時產生的資訊、警告與錯誤訊息,並存在下列變體:

  • Debug.LogWarning:列印警告訊息。

  • Debug.LogError:列印錯誤訊息。

Debug.Log 用於列印腳本執行時產生的資訊、警告與錯誤訊息,並存在下列變體:

  • Debug.LogWarning:列印警告訊息。

  • Debug.LogError:列印錯誤訊息。

  • Debug.LogAssertion:列印斷言訊息,斷言僅使用於開發測試階段。觸發時代表腳本發生致命錯誤,應強制中斷執行。與錯誤訊息的差別在於,錯誤訊息可以用於不會嚴重影響腳本運作或存在能夠自動修復的狀況。

Debug.Log 輸出的紀錄會顯示於 Console 面板中,請參考:[Unity] Console 面板

基礎語法

直接輸入字串、數值或任何物件作為參數。

1Debug.Log("Test");
2Debug.LogWarning("Test");
3Debug.LogError("Test");
4Debug.LogAssertion("Test");

進階語法一

於字串雙引號前加入 $ 符號,並於字串中使用大括號並輸入欲列印資料。

1var minute = System.DateTime.Now.Minute;
2var second = System.DateTime.Now.Second;
3
4Debug.Log($"Time - {minute}:{second}");
5Debug.LogWarning($"Time - {minute}:{second}");
6Debug.LogError($"Time - {minute}:{second}");
7Debug.LogAssertion($"Time - {minute}:{second}");

進階語法二

使用 Format 變體來組合參數至字串,於字串中使用大括號並標記編號,並於第二參數開始輸入參數 (編號對應參數順序,編號應從 0 開始標記)。

1var minute = System.DateTime.Now.Minute;
2var second = System.DateTime.Now.Second;
3
4Debug.LogFormat("Time - {0}:{1}", minute, second);
5Debug.LogWarningFormat("Time - {0}:{1}", minute, second);
6Debug.LogErrorFormat("Time - {0}:{1}", minute, second);
7Debug.LogAssertionFormat("Time - {0}:{1}", minute, second);

進階語法三

Debug.Log 支援 Rich Text,可以控制紀錄的字型大小、顏色等屬性,使用 XML 進行標記。

 1// 粗體
 2Debug.Log("<b>Test</b>");
 3
 4// 斜體
 5Debug.Log("<i>Test</i>");
 6
 7// 大小
 8Debug.Log("<size=23>Test</size>");
 9
10// 顏色
11Debug.Log("<color=#ff000077>Test</color>");

執行結果:

參考資料

相關文章

Ted Liou

雲科碩士在讀中,專注於 Unity C#、TouchDesigner 技術。
只要願意以超連結標註本文,歡迎轉載或用於教材製作!