Unity outputs Console content in Game

In Unity, sometimes I am too lazy to break the point to check. I believe many people will also use Debug.Log to output some content data, etc.

It is convenient to view the data or content of the code operation

However, the packaged project cannot display the content of the Console, which causes a lot of headaches. Sometimes it runs well on Unity.

But as soon as it was packaged, bugs started to appear and I couldn’t check it.  

For these situations, it is best to output Console content in Game

code part

The namespace is as follows

using System.Collections.Generic;
using UnityEngine;

 code part

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

Just mount any prefab

 

Guess you like

Origin blog.csdn.net/q1295006114/article/details/130347813
Recommended