86 lines
2.5 KiB
C#
86 lines
2.5 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using TMPro;
|
||
using UnityEngine;
|
||
using UnityEngine.UI;
|
||
using ZXKFramework;
|
||
|
||
public class RuntimeLogVisualizer : MonoBehaviour
|
||
{
|
||
private Text logText; // 关联TextMeshPro组件
|
||
private int maxLines = 200; // 最大显示行数(避免性能问题)
|
||
[SerializeField] private bool showInRelease = true; // 发布版本是否显示
|
||
|
||
private Queue<string> logQueue = new Queue<string>();
|
||
|
||
Queue<GameObject> log_TxtQue = new Queue<GameObject>();
|
||
private void Awake()
|
||
{
|
||
// 发布版本默认隐藏(可选)
|
||
if (!showInRelease && !Debug.isDebugBuild)
|
||
{
|
||
gameObject.SetActive(false);
|
||
return;
|
||
}
|
||
|
||
// 注册日志回调
|
||
Application.logMessageReceived += AddLog;
|
||
}
|
||
|
||
private void OnDestroy()
|
||
{
|
||
Application.logMessageReceived -= AddLog;
|
||
}
|
||
int num = 0;
|
||
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 > 1000)
|
||
{
|
||
logQueue.Dequeue();
|
||
}
|
||
// 更新UI文本
|
||
//logText.text = string.Join("", logQueue);
|
||
GameObject go = GameObject_Pool.Instance.TakeOutGame("log_Txt", transform);
|
||
go.SetActive(true);
|
||
num++;
|
||
go.name = num.ToString();
|
||
go.GetComponent<TMP_Text>().text = logQueue.Dequeue();
|
||
go.transform.SetAsLastSibling();
|
||
log_TxtQue.Enqueue(go);
|
||
|
||
//GameObject go = Resources.Load<GameObject>("log_Txt");
|
||
//GameObject obj = GameObject.Instantiate(go, transform);
|
||
if (log_TxtQue.Count >= 200)
|
||
{
|
||
int num = log_TxtQue.Count - 199;
|
||
for (int i = 0; i < num; i++)
|
||
{
|
||
GameObject g = log_TxtQue.Dequeue();
|
||
g.SetActive(false);
|
||
GameObject_Pool.Instance.PutInGame("log_Txt", g);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 可选:添加清空日志的方法(绑定到UI按钮)
|
||
public void ClearLogs()
|
||
{
|
||
logQueue.Clear();
|
||
logText.text = "";
|
||
}
|
||
}
|