LoginSignup
28
17

More than 5 years have passed since last update.

UnityのLogを簡易的に実行画面に表示する

Last updated at Posted at 2015-12-20

背景

UnityのログはEditor上ではすぐ確認できるがビルド後は別のツールを立ち上げたりやや面倒
また何気ないテストプレイ中にエラーが発生した場合でも問題箇所をすぐに特定したい

目的

Debug.LogError等の情報を実行画面に表示しアプリ単体で確認できるようにする

テストコード

using UnityEngine;
using System.Collections.Generic;

public class Test : MonoBehaviour {
    private const int LOG_MAX = 10;
    private Queue<string> logStack = new Queue<string>(LOG_MAX);

    void Awake() {
        Application.logMessageReceived += LogCallback;  // ログが書き出された時のコールバック設定

        Debug.LogWarning("hogehoge");   // テストでワーニングログをコール
    }

    /// <summary>
    /// ログを取得するコールバック
    /// </summary>
    /// <param name="condition">メッセージ</param>
    /// <param name="stackTrace">コールスタック</param>
    /// <param name="type">ログの種類</param>
    public void LogCallback(string condition, string stackTrace, LogType type) {
        // 通常ログまで表示すると邪魔なので無視
        if (type == LogType.Log)
            return;

        string trace = null;
        string color = null;

        switch (type) {
            case LogType.Warning:
                // UnityEngine.Debug.XXXの冗長な情報をとる
                trace = stackTrace.Remove(0, (stackTrace.IndexOf("\n") + 1));
                color = "yellow";
                break;
            case LogType.Error:
            case LogType.Assert:
                // UnityEngine.Debug.XXXの冗長な情報をとる
                trace = stackTrace.Remove(0, (stackTrace.IndexOf("\n") + 1));
                color = "red";
                break;
            case LogType.Exception:
                trace = stackTrace;
                color = "red";
                break;
        }

        // ログの行制限
        if (this.logStack.Count == LOG_MAX)
            this.logStack.Dequeue();

        string message = string.Format("<color={0}>{1}</color> <color=white>on {2}</color>", color, condition, trace);
        this.logStack.Enqueue(message);
    }

    /// <summary>
    /// エラーログ表示
    /// </summary>
    void OnGUI() {
        if (this.logStack == null || this.logStack.Count == 0)
            return;

        // 表示領域は任意
        float space = 16f;
        float height = 150f;
        Rect drawArea = new Rect(space, (float)Screen.height - height - space, (float)Screen.width * 0.5f, height);
        GUI.Box(drawArea, "");

        GUILayout.BeginArea(drawArea);
        {
            GUIStyle style = new GUIStyle();
            style.wordWrap = true;
            foreach (string log in logStack)
                GUILayout.Label(log, style);
        }
        GUILayout.EndArea();
    }
}

結果

キャプチャ.PNG

まとめ

単純な処理だがアプリケーションを実行中に問題が発生した際に割とすぐ気づける
ただしあくまで開発用なのでDebugSymbol等でリリースビルドには含めないようにする

28
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
17