65 lines
1.7 KiB
C#
65 lines
1.7 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using TMPro;
|
||
using UnityEngine;
|
||
using UnityEngine.UI;
|
||
|
||
public class RuntimeLogVisualizer : MonoBehaviour
|
||
{
|
||
[SerializeField] private Text logText; // 关联TextMeshPro组件
|
||
[SerializeField] private int maxLines = 1000; // 最大显示行数(避免性能问题)
|
||
[SerializeField] private bool showInRelease = true; // 发布版本是否显示
|
||
|
||
private Queue<string> logQueue = new Queue<string>();
|
||
|
||
private void Awake()
|
||
{
|
||
// 发布版本默认隐藏(可选)
|
||
if (!showInRelease && !Debug.isDebugBuild)
|
||
{
|
||
gameObject.SetActive(false);
|
||
return;
|
||
}
|
||
|
||
// 注册日志回调
|
||
Application.logMessageReceived += AddLog;
|
||
}
|
||
|
||
private void OnDestroy()
|
||
{
|
||
Application.logMessageReceived -= AddLog;
|
||
}
|
||
|
||
private void AddLog(string log, string stack, LogType type)
|
||
{
|
||
// 按日志类型着色
|
||
string color = type switch
|
||
{
|
||
LogType.Error or LogType.Exception => "#FF0000", // 红色
|
||
LogType.Warning => "#FFFF00", // 黄色
|
||
LogType.Assert => "#FF8800", // 橙色
|
||
_ => "#FFFFFF" // 白色(普通日志)
|
||
};
|
||
|
||
// 格式化日志(带时间戳)
|
||
string formattedLog = $"[{System.DateTime.Now:HH:mm:ss}] <color={color}>{log}</color>\n";
|
||
|
||
// 控制日志数量(超出则移除最早的)
|
||
logQueue.Enqueue(formattedLog);
|
||
if (logQueue.Count > maxLines)
|
||
{
|
||
logQueue.Dequeue();
|
||
}
|
||
|
||
// 更新UI文本
|
||
logText.text = string.Join("", logQueue);
|
||
}
|
||
|
||
// 可选:添加清空日志的方法(绑定到UI按钮)
|
||
public void ClearLogs()
|
||
{
|
||
logQueue.Clear();
|
||
logText.text = "";
|
||
}
|
||
}
|