Unity将调试信息输出到屏幕上

  本文介绍,在Unity3D中,如何将Debug.Log()的信息输出到屏幕窗口上。
1.新建一个cs脚本:ConsoleToScreen.cs,
2.写入以下内容:

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

/// 
/// 用于把Debug.Log的信息输出到游戏窗口中
/// 
public class ConsoleToScreen : MonoBehaviour
{
    /// 一页展示多少行
    private const int maxLines = 50;
    /// 一行有多少个字
    private const int maxLineLength = 80;
    /// 输出的字体大小
    private const int fontSize = 20;
    /// 字体颜色
    private readonly Color fontColor = Color.red;

    private string _logStr = "";
    private readonly List<string> _lines = new List<string>();

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

    public void Log(string logString, string stackTrace, LogType type)
    {
        foreach (var line in logString.Split('\n'))
        {
            if (line.Length <= maxLineLength)
            {
                _lines.Add(line);
                continue;
            }
            var lineCount = line.Length / maxLineLength + 1;
            for (int i = 0; i < lineCount; i++)
            {
                if ((i + 1) * maxLineLength <= line.Length)
                {
                    _lines.Add(line.Substring(i * maxLineLength, maxLineLength));
                }
                else
                {
                    _lines.Add(line.Substring(i * maxLineLength, line.Length - i * maxLineLength));
                }
            }
        }
        if (_lines.Count > maxLines)
        {
            _lines.RemoveRange(0, _lines.Count - maxLines);
        }
        _logStr = string.Join("\n", _lines);
    }

    private void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
           new Vector3(1f, 1f, 1.0f));
        GUI.Label(new Rect(10, 10, 600, 370), _logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize), normal = new GUIStyleState() { textColor = fontColor } });
    }
}

有四个参数可以设置:maxLines、maxLineLength、fontSize、fontColor。
3.将脚本随便挂到一个场景中的物体上就好了。

你可能感兴趣的:(unity)