100 lines
3.0 KiB
C#
100 lines
3.0 KiB
C#
![]() |
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using Prefab;
|
||
|
using TMPro;
|
||
|
using UnityEngine;
|
||
|
|
||
|
namespace UI
|
||
|
{
|
||
|
public class LogUI : UIBase
|
||
|
{
|
||
|
public Transform contentPanel; // 日志内容容器
|
||
|
public TextPrefab textPrefab; // 文本预制体引用
|
||
|
|
||
|
// 日志类型颜色映射
|
||
|
private static readonly Dictionary<LogType, Color> logColors = new Dictionary<LogType, Color>
|
||
|
{
|
||
|
{ LogType.Log, Color.white },
|
||
|
{ LogType.Warning, Color.yellow },
|
||
|
{ LogType.Error, new Color(1f, 0.4f, 0.4f) },
|
||
|
{ LogType.Exception, new Color(1f, 0.2f, 0.2f) },
|
||
|
{ LogType.Assert, new Color(0.8f, 0.4f, 1f) }
|
||
|
};
|
||
|
|
||
|
private List<Transform> _logItems = new List<Transform>(); // 已创建的日志条目
|
||
|
private int _lastLogCount = 0; // 上次显示的日志数量
|
||
|
|
||
|
private void Start()
|
||
|
{
|
||
|
Logging.LogCapturer.Clear();
|
||
|
}
|
||
|
|
||
|
public override void Show()
|
||
|
{
|
||
|
base.Show();
|
||
|
RefreshLogDisplay();
|
||
|
}
|
||
|
|
||
|
private void RefreshLogDisplay()
|
||
|
{
|
||
|
var logs = Logging.LogCapturer.GetLogs();
|
||
|
|
||
|
// 如果日志数量减少,清理多余的条目
|
||
|
if (logs.Count < _lastLogCount)
|
||
|
{
|
||
|
for (int i = logs.Count; i < _lastLogCount; i++)
|
||
|
{
|
||
|
Destroy(_logItems[i].gameObject);
|
||
|
}
|
||
|
|
||
|
_logItems.RemoveRange(logs.Count, _logItems.Count - logs.Count);
|
||
|
}
|
||
|
|
||
|
// 更新现有条目
|
||
|
for (int i = 0; i < Math.Min(logs.Count, _logItems.Count); i++)
|
||
|
{
|
||
|
UpdateLogEntry(_logItems[i], logs[logs.Count - 1 - i]);
|
||
|
}
|
||
|
|
||
|
// 添加新的条目
|
||
|
if (logs.Count > _lastLogCount)
|
||
|
{
|
||
|
for (int i = _lastLogCount; i < logs.Count; i++)
|
||
|
{
|
||
|
CreateLogEntry(logs[logs.Count - 1 - i]);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_lastLogCount = logs.Count;
|
||
|
}
|
||
|
|
||
|
private void CreateLogEntry(Logging.LogCapturer.LogEntry entry)
|
||
|
{
|
||
|
// 实例化文本预制体
|
||
|
var logItem = Instantiate(textPrefab, contentPanel);
|
||
|
_logItems.Add(logItem.transform);
|
||
|
|
||
|
UpdateLogEntry(logItem.transform, entry);
|
||
|
}
|
||
|
|
||
|
private void UpdateLogEntry(Transform logItemTransform, Logging.LogCapturer.LogEntry entry)
|
||
|
{
|
||
|
var logItem = logItemTransform.GetComponent<TextPrefab>();
|
||
|
|
||
|
// 设置文本内容
|
||
|
logItem.Label = entry.ToString();
|
||
|
|
||
|
// 设置文本颜色(根据日志类型)
|
||
|
if (logColors.TryGetValue(entry.Type, out Color color))
|
||
|
{
|
||
|
logItem.text.color = color;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
logItem.text.color = Color.white; // 默认颜色
|
||
|
}
|
||
|
|
||
|
logItem.text.alignment = TextAlignmentOptions.TopLeft;
|
||
|
}
|
||
|
}
|
||
|
}
|