Files
Echo/Assets/_Project/Scripts/Utils/RuntimeDebugConsole.cs
T

93 lines
2.6 KiB
C#
Raw Normal View History

2026-07-08 19:53:15 +08:00
using UnityEngine;
using System.Collections.Generic;
namespace Utils
{
public class RuntimeDebugConsole : MonoBehaviour
{
private List<string> logs = new List<string>();
private Vector2 scrollPosition;
private bool showConsole = false;
private GUIStyle logStyle;
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void OnEnable()
{
Application.logMessageReceived += HandleLog;
}
void OnDisable()
{
Application.logMessageReceived -= HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
string color = "white";
if (type == LogType.Error || type == LogType.Exception) color = "red";
else if (type == LogType.Warning) color = "yellow";
// Only store message, stack trace might be too long for small console
logs.Add($"<color={color}>[{type}] {logString}</color>");
if (logs.Count > 50)
{
logs.RemoveAt(0);
}
// Scroll to bottom
scrollPosition.y = float.MaxValue;
}
void Update()
{
// Toggle console with Backquote (~) key
if (Input.GetKeyDown(KeyCode.BackQuote))
{
showConsole = !showConsole;
}
}
void OnGUI()
{
if (!showConsole) return;
if (logStyle == null)
{
logStyle = new GUIStyle(GUI.skin.label);
logStyle.richText = true;
logStyle.wordWrap = true;
}
// Draw a semi-transparent background
GUI.Box(new Rect(0, 0, Screen.width, Screen.height * 0.5f), "Debug Console (Press ` to toggle)");
GUILayout.BeginArea(new Rect(10, 20, Screen.width - 20, Screen.height * 0.5f - 40));
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (var log in logs)
{
GUILayout.Label(log, logStyle);
}
GUILayout.EndScrollView();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Clear", GUILayout.Width(100)))
{
logs.Clear();
}
if (GUILayout.Button("Close", GUILayout.Width(100)))
{
showConsole = false;
}
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
}
}