OnScreen / Live Console for Unity

Today I made a small utility to ease the always annoying task of online debugging. It prints in the screen the console output, so you are able to know whats going on there.

I wish I could have overrided Unity's Debug class, but it's sealed, so I had to replace all the Debug.Log... by my GUIConsole.Log...

As I said it's a simple thing, but very useful when you are making online debugging or other tricky things:

/// <summary>
/// Shows logs message in the GUI
/// </summary>
public class GUIConsole : MonoBehaviour
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
#region Singleton
private static GUIConsole instance = null;

public static GUIConsole Instance
{
get
{
return instance;
}
}
#endregion

#region Member Variables
public bool debugActivated = true; //To control the component activation
public bool showLog = true;
public static int size = 20; //Max number of messages in the queue

private static string log = ""; //will hold the whole output
private static Queue<string> logQueue = new Queue<string>(); //queue of log messages
#endregion

#region Unity methods
void Awake()
{
instance = this;
DontDestroyOnLoad (this.gameObject);
}

void OnGUI()
{
if (debugActivated)
{
if (GUILayout.Button ("Clear Log", GUILayout.Width (100), GUILayout.Height (25)))
{
log = "";
logQueue.Clear();
}

if (GUILayout.Button ("Hide Log", GUILayout.Width (100), GUILayout.Height (25)))
{
showLog = !showLog;
}

if (showLog)
{
GUI.TextArea (new Rect (420, 5, Screen.width - 425, Screen.height - 10), log);
}
}
}
#endregion

#region Overrides
public static void Log (object _message)
{
ManageLog (_message.ToString (), LogType.Log);
Debug.Log (_message);
}

public static void LogWarning (object _message)
{
ManageLog (_message.ToString (), LogType.Warning);
Debug.LogWarning (_message);
}

public static void LogError (object _message)
{
ManageLog (_message.ToString (), LogType.Error);
Debug.LogError (_message);
}

private static void ManageLog (string logString, LogType logType)
{
if(logQueue.Count > size)
{
logQueue.Dequeue();
}

string prefix = "";
string suffix = "";

ManageSeverity (logType, ref prefix, ref suffix);

logQueue.Enqueue(prefix + logString + suffix);
log = "";

foreach(string logEntry in logQueue.ToArray()){
log = log + "\n\n" + logEntry;
}
}

private static void ManageSeverity(LogType _type, ref string _prefix, ref string _suffix)
{
switch (_type)
{
case LogType.Error:
_prefix = "<color=red>";
break;
case LogType.Log:
_prefix = "<color=blue>";
break;
case LogType.Warning:
_prefix = "<color=yellow>";
break;
}
_suffix = "</color>";
}

#endregion
#endif
}

Comentarios

Entradas populares