UnityのDebug.Logをゲーム画面に表示する
Photonでオンラインゲームを作っていると、2窓以上でDebug.Logのメッセージを取得したい場合が必ずあります。今回はその方法を紹介します。
まずはソースの作成でLogMenu.csという以下の様にコード書きます。
LogMenu.cs
using UnityEngine;
using UnityEngine.UI;
public class LogMenu : MonoBehaviour
{
[SerializeField]
private Text m_textUI = null;
private void Awake()
{
Application.logMessageReceived += OnLogMessage;
}
private void OnDestroy()
{
Application.logMessageReceived += OnLogMessage;
}
private void OnLogMessage(string i_logText, string i_stackTrace, LogType i_type)
{
if (string.IsNullOrEmpty(i_logText))
{
return;
}
// 下のチェックがないとMissingReferenceExceptionThe object of type "Text" has been destroyedが起こるので注意
if (m_textUI == null)
{
return;
}
if (!string.IsNullOrEmpty(i_stackTrace))
{
switch (i_type)
{
case LogType.Error:
case LogType.Assert:
case LogType.Exception:
i_logText += System.Environment.NewLine + i_stackTrace;
break;
default:
break;
}
}
switch (i_type)
{
case LogType.Error:
case LogType.Assert:
case LogType.Exception:
i_logText = string.Format("<color=red>{0}</color>", i_logText);
break;
case LogType.Warning:
i_logText = string.Format("<color=yellow>{0}</color>", i_logText);
break;
default:
break;
}
m_textUI.text += i_logText + System.Environment.NewLine;
}
} // class LogMenu
スクロール機能付きのキャンバスの作成
- UI→ScrollViewで作成した後、DebugCanvasと名前を変更
- DebugCanvasにLogMenu.csをアタッチ
- Contentを下の図のようにTextUIにアタッチ
もし3の前にContentにTextがついてなかったら、AddComponetでTextを追加しましょう。

実行結果

これでDebug.LogをconsolだけでなくCanvasにも表示することができました!