simplestarの技術ブログ

目的を書いて、思想と試行、結果と考察、そして具体的な手段を記録します。

Unity:uGUIにDebug.Logの内容を表示する方法1

UnityでDebug.Logした内容を、uGUIのUI画面でゲーム実行中に確認したい場合があります。
今回はその要望に応える形で次のようにログが流れる仕組みを作ったので、今後自分が再利用するために公開します。

f:id:simplestar_tech:20170319195427j:plain

Debug.Log をハンドリングするコードは次の通り

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UILogBehaviour : MonoBehaviour {

    public Text TextPrefab;
    private RectTransform _myPanel;

	// Use this for initialization
	void Start () {
        _myPanel = GetComponent<RectTransform>();
    }
	
	// Update is called once per frame
	void Update () {
		
	}

    void OnEnable()
    {
        Application.logMessageReceived += Log;
    }

    void OnDisable()
    {
        Application.logMessageReceived -= Log;
    }

    public void Log(string logString, string stackTrace, LogType type)
    {
        Text logLine = Instantiate(TextPrefab, Vector3.zero, Quaternion.identity, _myPanel);
        logLine.name = "LogLine";
        logLine.text = logString;

        if (20 < _myPanel.transform.childCount)
        {
            Transform child = _myPanel.GetChild(1);
            GameObject.Destroy(child.gameObject);
        }
    }
}

使い方:このスクリプトを VerticalLayoutGroup コンポーネントを付けた Panel に追加して、最初の子要素の Text を TextPrefab に渡します。

すると 20 件以上ログが流れたら、古いログのラインから順番に消えていきます。
テスト用に Space キーを押したらログが流れる仕組みを次のように書いて、テストしました。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DeviceCameraBehaviour : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Time = " + Time.time.ToString("000.0000"));
        }
	}
}

Android などの実機で、デバイスの設定がどうなっているかなどを簡易に確認する方法として使えると思い、作ってみました。
以上です。