Skip to content

Instantly share code, notes, and snippets.

@gluschenko
Created August 19, 2015 19:28
Show Gist options
  • Save gluschenko/d0e74dce1dd7ebdf9fcd to your computer and use it in GitHub Desktop.
Save gluschenko/d0e74dce1dd7ebdf9fcd to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
using System.Collections.Generic;
public class DebugConsole : MonoBehaviour
{
struct ConsoleMessage
{
public readonly string message;
public readonly string stackTrace;
public readonly LogType type;
public ConsoleMessage (string message, string stackTrace, LogType type)
{
this.message = message;
this.stackTrace = stackTrace;
this.type = type;
}
}
List<ConsoleMessage> entries = new List<ConsoleMessage>();
Vector2 scrollPos;
bool show;
bool collapse;
public GUISkin skin;
// Visual elements:
const int margin = 40;
Rect windowRect = new Rect(margin, margin, Screen.width - (2 * margin), 400);
void OnEnable ()
{
Application.RegisterLogCallback(HandleLog);
}
void OnDisable ()
{
Application.RegisterLogCallback(null);
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.F4)||Input.GetKeyDown(KeyCode.K))
{
show = !show;
}
}
void OnGUI ()
{
GUI.skin = skin;
if (show) {
windowRect = GUILayout.Window(123456, windowRect, ConsoleWindow, "Console");
}
}
void ConsoleWindow (int windowID)
{
scrollPos = GUILayout.BeginScrollView(scrollPos);
GUI.skin = null;
for (int i = 0; i < entries.Count; i++) {
ConsoleMessage entry = entries[i];
if (collapse && i > 0 && entry.message == entries[i - 1].message) {
continue;
}
switch (entry.type)
{
case LogType.Error:
GUI.contentColor = Color.red;
break;
case LogType.Exception:
GUI.contentColor = Color.red;
break;
case LogType.Warning:
GUI.contentColor = Color.yellow;
break;
default:
GUI.contentColor = Color.white;
break;
}
GUILayout.Label(entry.message);
}
GUI.contentColor = Color.white;
GUI.skin = skin;
GUILayout.EndScrollView();
GUILayout.BeginHorizontal();
// Clear button
if (GUILayout.Button("Clear log", GUILayout.Width(100), GUILayout.Height(30))) {
entries.Clear();
}
// Collapse toggle
if (GUILayout.Button("Collapse", GUILayout.Width(100), GUILayout.Height(30)))
{
collapse = !collapse;
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Close", GUILayout.Width(100), GUILayout.Height(30))) {
show = false;
}
GUILayout.EndHorizontal();
// Set the window to be draggable by the top title bar
GUI.DragWindow(new Rect(0, 0, 10000, 20));
}
void HandleLog (string message, string stackTrace, LogType type)
{
ConsoleMessage entry = new ConsoleMessage(message, stackTrace, type);
entries.Add(entry);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment