This repository has been archived on 2025-04-28. You can view files and clone it, but cannot push or open issues or pull requests.
ARPlusSystem/ARPlusSystem-250418/Assets/Scripts/Util/UGUILogger.cs

69 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Util
{
public class UGUILogger : MonoBehaviour
{
public Text logText;
private readonly StringBuilder logContent = new StringBuilder();
public ScrollRect scrollRect;
public int maxLines = 10000; // 最大允许行数
private readonly Queue<string> logQueue = new Queue<string>();
public float autoScrollDelay = 10f;
private Coroutine autoScrollCoroutine;
private bool isUserInteracting;
void Start()
{
Application.logMessageReceived += (logString, trace, type) => {
if(logString.Contains("[Info]")) { // 筛选Gameplay标签
AddLog(logString);
}
};
}
public void ClearLog() {
logContent.Clear();
logText.text = "";
}
public void AddLog(string newLog)
{
logQueue.Enqueue(newLog);
// 动态拼接文本
logText.text = string.Join("\n", logQueue);
// 强制刷新布局(关键!)
LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRect.content);
}
void Update()
{
// 强制滚动条位置置底0为底部1为顶部
scrollRect.verticalNormalizedPosition = 0;
if (logQueue.Count > maxLines)
{
// 触发清空操作
logQueue.Clear();
logText.text = "";
// 重置滚动条位置
scrollRect.verticalNormalizedPosition = 1;
}
}
}
public enum LogTag
{
Info,
Warning
}
public static class CustomLogger {
public static void LogWithTag(string message, LogTag tag) {
Debug.Log($"[{tag}][{DateTime.Now:yyyy-MM-dd HH:mm:ss}]{message}");
}
}
}