Unity,将控制台输出的warning、error、log显示到游戏界面中,以便打包出来测试使用

 

主要就是一个回调函数 Application.logMessageReceived

 

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

public class DebuggerLog : MonoBehaviour {


    public struct LogInfo
    {
        public LogType type;
        public string desc;

        public LogInfo(LogType type, string desc)
        {
            this.type = type;
            this.desc = desc;
        }
    }

    //错误详情
    public List<LogInfo> m_logEntries = new List<LogInfo>();
    public List<LogInfo> m_logLog = new List<LogInfo>();
    public List<LogInfo> m_logWarning = new List<LogInfo>();
    public List<LogInfo> m_logError = new List<LogInfo>();
    public List<LogInfo> curLog = new List<LogInfo>();
    //是否显示错误窗口
    private bool m_IsVisible = false;
    //窗口显示区域
    private Rect m_WindowRect = new Rect(0, 0, Screen.width, Screen.height);
    //窗口滚动区域
    private Vector2 m_scrollPositionText = Vector2.zero;
    //字体大小
    private int fontSize = 30;

    public List<string> s1 = new List<string>();

    GUISkin skin;

    private void Start()
    {
        skin = Resources.Load<GUISkin>("GUISkin");
        curLog = m_logEntries;
        监听错误
        Application.logMessageReceivedThreaded += (condition, stackTrace, type) =>
        {
            if (!m_IsVisible)
            {
                m_IsVisible = true;
            }
            switch (type)
            {
                case LogType.Warning:
                    m_logWarning.Add(new LogInfo(type, string.Format("{0}\n{1}", condition, stackTrace)));
                    break;
                case LogType.Log:
                    m_logLog.Add(new LogInfo(type, string.Format("{0}\n{1}", condition, stackTrace)));
                    break;
                case LogType.Error:
                case LogType.Exception:
                    m_logError.Add(new LogInfo(type, string.Format("{0}\n{1}", condition, stackTrace)));
                    break;
            }
            m_logEntries.Add(new LogInfo(type, string.Format("{0}\n{1}", condition, stackTrace)));
            s1.Add(stackTrace);
        };

        for (int i = 0; i < 10; i++)
        {
            Debug.LogError("错误啊!!");
            Debug.LogWarning("警告啊!!");
            print("正常输出");
        }
        int[] a = null;
        a[1] = 100;
    }

    void OnGUI()
    {
        if (m_IsVisible)
        {
            m_WindowRect = GUILayout.Window(0, m_WindowRect, ConsoleWindow, "Console");
        }
    }

    //日志窗口
    void ConsoleWindow(int windowID)
    {
        GUILayout.BeginHorizontal();
        skin.button.fontSize = fontSize;
        skin.textArea.fontSize = fontSize;
        if (GUILayout.Button("Clear", skin.button, GUILayout.MaxWidth(200),GUILayout.MaxHeight(100)))
        {
            m_logEntries.Clear();
        }
        if (GUILayout.Button("Close", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            m_IsVisible = false;
        }
        if (GUILayout.Button("AddFontSize", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            fontSize++;
        }
        if (GUILayout.Button("ReduceFontSize", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            fontSize--;
        }
        if (GUILayout.Button("Log", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            if (curLog == m_logLog)
                curLog = m_logEntries;
            else
                curLog = m_logLog;
        }
        if (GUILayout.Button("Warning", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            if (curLog == m_logWarning)
                curLog = m_logEntries;
            else
                curLog = m_logWarning;
        }
        if (GUILayout.Button("Error", skin.button, GUILayout.MaxWidth(200), GUILayout.MaxHeight(100)))
        {
            if (curLog == m_logError)
                curLog = m_logEntries;
            else
                curLog = m_logError;
        }
        GUILayout.EndHorizontal();
        m_scrollPositionText = GUILayout.BeginScrollView(m_scrollPositionText,skin.horizontalScrollbar,skin.verticalScrollbar);
        foreach (var entry in curLog)
        {
            Color currentColor = GUI.contentColor;
            switch (entry.type)
            {
                case LogType.Warning:
                    GUI.contentColor = Color.white;
                    break;
                case LogType.Assert:
                    GUI.contentColor = Color.black;
                    break;
                case LogType.Log:
                    GUI.contentColor = Color.green;
                    break;
                case LogType.Error:
                case LogType.Exception:
                    GUI.contentColor = Color.red;
                    break;
            }
            GUILayout.Label(entry.desc, skin.textArea);
            GUI.contentColor = currentColor;
        }
        GUILayout.EndScrollView();
    }

}

结果图

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 `Process` 运行的控制台输出显示Unity ,可以使用 `Process` 对象的 `OutputDataReceived` 事件和 `ErrorDataReceived` 事件来捕获进程的标准输出和错误输出。然后可以将输出信息添加到一个字符串缓冲区,并在 Unity 显示。 以下是一个示例代码: ```csharp using System.Diagnostics; using UnityEngine; public class ProcessTest : MonoBehaviour { private Process process; private string outputText = ""; void Start() { process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c dir"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.EnableRaisingEvents = true; process.OutputDataReceived += OnOutputDataReceived; process.ErrorDataReceived += OnErrorDataReceived; process.Exited += OnProcessExited; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { outputText += e.Data + "\n"; } } void OnErrorDataReceived(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { outputText += e.Data + "\n"; } } void OnProcessExited(object sender, System.EventArgs e) { UnityEngine.Debug.Log("Process exited."); } void OnGUI() { GUILayout.Label(outputText); } void OnDestroy() { if (process != null && !process.HasExited) { process.Kill(); } } } ``` 在这个示例,我们使用 `Process` 对象启动一个 `cmd.exe` 进程,并运行 `dir` 命令。然后,我们将 `OutputDataReceived` 和 `ErrorDataReceived` 事件处理程序分别绑定到 `OnOutputDataReceived` 和 `OnErrorDataReceived` 方法,当进程有输出时,就会将输出信息添加到 `outputText` 字符串缓冲区。最后,我们在 `OnGUI` 方法将 `outputText` 显示Unity 。 需要注意的是,由于 `OnGUI` 方法是在主线程调用的,如果 `Process` 对象在主线程启动,则可能会导致 Unity 卡死。因此,建议将 `Process` 对象的启动和事件处理程序绑定放在一个单独的线程执行,以避免主线程被阻塞。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值