如何将Unity的Debug.Log日志输出到屏幕或GUI界面
解决方案1:UGUI 屏幕日志组件(适配正式项目)
核心原理是注册Unity全局日志回调,自动捕获所有运行时日志输出,绑定到UI组件显示,可自定义样式,适配正式发布环境。
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; // 若使用TextMeshPro,将所有Text类型替换为TMP_Text即可 [RequireComponent(typeof(Text))] public class ScreenLogger : MonoBehaviour { [Header("日志配置")] public int maxLogCount = 20; public bool showLog = true; public Color logColor = Color.white; public Color warningColor = Color.yellow; public Color errorColor = Color.red; private Text _logText; private Queue<string> _logQueue = new Queue<string>(); void Awake() { _logText = GetComponent<Text>(); // 跨场景保留日志组件 DontDestroyOnLoad(gameObject); // 注册全局日志回调 Application.logMessageReceived += HandleLog; } void HandleLog(string logString, string stackTrace, LogType type) { if (!showLog) return; // 不同日志类型标记不同颜色 string colorHex = type switch { LogType.Warning => ColorUtility.ToHtmlStringRGBA(warningColor), LogType.Error or LogType.Exception => ColorUtility.ToHtmlStringRGBA(errorColor), _ => ColorUtility.ToHtmlStringRGBA(logColor) }; string formattedLog = $"<color=#{colorHex}>{logString}</color>\n"; // 限制最大日志条数防止内容溢出 _logQueue.Enqueue(formattedLog); if (_logQueue.Count > maxLogCount) _logQueue.Dequeue(); _logText.text = string.Join("", _logQueue.ToArray()); } void OnDestroy() { // 注销回调避免内存泄漏 Application.logMessageReceived -= HandleLog; } }
使用步骤:
- 在场景中新建UI Text/TextMeshPro组件,调整位置到屏幕边缘,设置合适的字体大小与宽高
- 将上述脚本挂载到UI组件上,打包运行后即可自动显示所有日志
- 可自行添加快捷键逻辑(比如按F3切换显隐),避免日志挡住操作界面
解决方案2:OnGUI 轻量日志控制台(适合快速测试)
无需依赖UGUI体系,脚本挂载后直接生效,适合多客户端快速测试场景。
using UnityEngine; using System.Collections.Generic; public class GUIScreenLogger : MonoBehaviour { public int maxLogCount = 15; public bool showConsole = true; public Vector2 offset = new Vector2(10, 10); public int fontSize = 14; private Queue<string> _logQueue = new Queue<string>(); private GUIStyle _textStyle; void Awake() { DontDestroyOnLoad(gameObject); Application.logMessageReceived += HandleLog; _textStyle = new GUIStyle(); _textStyle.fontSize = fontSize; _textStyle.normal.textColor = Color.white; } void HandleLog(string logString, string stackTrace, LogType type) { if (!showConsole) return; string logPrefix = type switch { LogType.Warning => "[警告] ", LogType.Error or LogType.Exception => "[错误] ", _ => "[日志] " }; _logQueue.Enqueue(logPrefix + logString); if (_logQueue.Count > maxLogCount) _logQueue.Dequeue(); } void OnGUI() { float y = offset.y; foreach (var log in _logQueue) { GUI.Label(new Rect(offset.x, y, Screen.width - offset.x * 2, fontSize + 2), log, _textStyle); y += fontSize + 5; } // 内置显隐切换按钮 if (GUI.Button(new Rect(Screen.width - 120, 10, 100, 30), "切换日志")) { showConsole = !showConsole; } } void OnDestroy() { Application.logMessageReceived -= HandleLog; } }
两种方案均兼容所有
Debug类的打印接口,原有日志代码无需任何修改即可生效。你可以额外增加日志过滤规则、本地持久化存储等自定义功能适配自身需求。
内容的提问来源于stack exchange,提问作者xjcl
相关产品推荐
相关产品推荐

