You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity编辑器中如何获取Debug窗口选中/悬停的错误消息?

Unity编辑器中获取Debug窗口选中错误消息的方案

1. 反射访问ConsoleWindow获取选中条目

Unity的Debug窗口对应UnityEditor.ConsoleWindow类型,由于官方未开放直接获取选中条目的公开API,可通过反射访问其内部私有字段实现:

using UnityEditor;
using UnityEngine;
using System.Reflection;

public class DebugSelectionTool : EditorWindow
{
    [MenuItem("Tools/获取选中调试消息")]
    public static void OpenTool()
    {
        GetWindow<DebugSelectionTool>("调试选择工具");
    }

    private void OnGUI()
    {
        if (GUILayout.Button("获取选中错误"))
        {
            var consoleWindow = EditorWindow.GetWindow<ConsoleWindow>();
            if (consoleWindow == null)
            {
                Debug.Log("未找到Debug窗口");
                return;
            }

            // 获取选中的日志条目对象
            var selectedEntryField = typeof(ConsoleWindow).GetField("m_SelectedEntry", BindingFlags.Instance | BindingFlags.NonPublic);
            var selectedEntry = selectedEntryField?.GetValue(consoleWindow);
            if (selectedEntry == null)
            {
                Debug.Log("未选中任何错误消息");
                return;
            }

            // 提取消息内容
            var messageField = selectedEntry.GetType().GetField("message", BindingFlags.Instance | BindingFlags.Public);
            var errorMessage = messageField?.GetValue(selectedEntry) as string;
            if (!string.IsNullOrEmpty(errorMessage))
            {
                Debug.Log($"选中的错误消息:\n{errorMessage}");
            }
        }
    }
}

注意:反射依赖Unity内部字段名,不同版本可能存在差异,测试时需对应你的Unity版本调整字段名(比如部分旧版本可能用m_LastClickedEntry替代m_SelectedEntry)。

2. 编辑器专用日志监听API

你之前使用的Application.logMessageReceived是运行时API,编辑器环境下需改用EditorApplication提供的日志监听事件:

using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class EditorLogCapture
{
    static EditorLogCapture()
    {
        // 监听编辑器所有日志
        EditorApplication.logMessageReceived += CaptureEditorLogs;
    }

    private static void CaptureEditorLogs(string message, string stackTrace, LogType logType)
    {
        if (logType == LogType.Error || logType == LogType.Exception)
        {
            // 实时捕获错误日志,可自行存储或处理
            Debug.Log($"捕获到编辑器错误:\n{message}");
        }
    }
}

这个方法能实时获取所有编辑器日志,但无法直接获取Debug窗口中已选中的条目,适合批量日志收集场景。

3. 额外提示

  • 编辑器工具代码必须放在Editor文件夹下,否则无法在编辑器中生效;
  • 反射访问内部API存在版本兼容性风险,若需长期维护,建议向Unity官方提交反馈,请求开放获取选中日志的公开API;
  • 若需获取日志的堆栈信息,可在反射时同时提取stackTrace字段。

内容的提问来源于stack exchange,提问作者Akuu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:32:41