I’ve provided a public repository with a couple of useful classes to help with GUI development. Feel free to add to them, extend them or use them in your personal projects.
When writing Auto Layout’d gui extensions with Unity, it’s always important to remember that almost every action has to have and opposite.
Example
Take GUILayout.BeginVertical, for example :
GUILayout.BeginVertical();
{
// Do something here
}
GUILayout.EndVertical();
This is all well and good, functionality wise, but the user must remember to EndVertical
Instead, with these Utility class, you can do the following.
using(new GUIBeginVertical())
{
// Do something here
}
Another Example
When setting the colour on GUI, you’ve got to remember to cache off the existing colour and re-apply it, not anymore.
var previousColour = GUI.Color;
GUI.color = Color.red;
{
// Do something with red GUI
}
GUI.color = previousColour;
becomes
using(new GUIChangeColor(Color.red))
{
// Do something with red GUI
}
With this new approach, the programmer doesn’t need to remember to EndVertical, the code takes care of that for them. This isn’t exactly revolutionary stuff, and is a commonly used programming idiom, if you’d like to know more, research RAII.
Nice approach, convinient for use, but what about productivity? “Using” keyword creates and disposes object, but OnGUI() method calls very often - up to some times per frame. So, I’m interesting how resonably using of big number of such classes?
The using keyword, wraps that chunk of code up in a try{} finally{} block, so if you’re generally steering clear, it would be best to do so here.
Although OnGUI is executed often for various events I’m never expecting to see any issues in the editor, I probably wouldn’t use this code at runtime, since you’d largely want to steer clear of adding any OnGUI methods.
Though I wouldn’t necessarily be so strict as to say never use this idiom at runtime, I have for example used this in the past, in game code to time a section of code. You can take the exact same approach, but in the constructor / dispose method grab the time and do a diff
using(new Timer())
PotentiallyExpensiveMethod();
using UnityEngine;
using System;
using System.Collections;
namespace WellFired
{
public class Timer : IDisposable
{
private float PreviousTime
{
get;
set;
}
private string TimerName
{
get;
set;
}
public Timer(string timerName)
{
PreviousTime = Time.deltaTime;
TimerName = timerName;
}
public void Dispose()
{
var timeDiff = Time.deltaTime - PreviousTime;
Debug.LogError (string.Format("[Timer {0}] took {1}", TimerName, timeDiff));
}
}
}
Note: That timer example is something I just nocked together for demonstration purposes, haven’t actually tested it.