Unity 在Game输出Console内容

在Unity 有的时候懒得打断点查看  相信很多人也会用Debug.Log输出一些内容数据等

方便查看代码运行的数据或内容

但是 打包后的项目没办法显示Console内容 让很多头疼  有的时候明明在unity上运行好好的

可是一打包就开始出现bug还没法查看  

向这些情况最好是在Game输出Console内容

代码部分

命名空间如下

using System.Collections.Generic;
using UnityEngine;

 代码部分

public class ConsoleToSceen : MonoBehaviour
{
    const int maxLines = 50;
    const int maxLineLength = 120;
    private string _logStr = "";

    private readonly List<string> _lines = new List<string>();
    void OnEnable() { Application.logMessageReceived += Log; }
    void OnDisable() { Application.logMessageReceived -= Log; }
    void Update() { }

    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);
    }

    void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
           new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
        GUI.Label(new Rect(10, 10, 800, 370), _logStr, new GUIStyle());
    }
}

挂载任意预制体即可

扫描二维码关注公众号,回复: 15697544 查看本文章

猜你喜欢

转载自blog.csdn.net/q1295006114/article/details/130347813