using UnityEngine; using System.Collections.Generic; namespace Utils { public class RuntimeDebugConsole : MonoBehaviour { private List logs = new List(); 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($"[{type}] {logString}"); 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(); } } }