How to Wrestle Down GUIs in Unity 3D

You are here

GUIs are not exactly easy to program in Unity 3D, since there is only one method available (OnGUI()) that obviously has to take up everything.

This becomes a problem as soon you try to create different menu screens that have to be switched out. One way to do it would probably be to use different scenes (which would be cumbersome); another way to use a switch, which would be just as cumbersome.

My way of doing it is using delegates, which allows to keep each screen encapsulated in a distinct method, while still retaining the same scene all the time.

using UnityEngine; using System.Collections; using System; //Necessary to access Action

///

/// An example for using delegates to show different menu screens. /// public class DelegateGUI : MonoBehaviour {

#region Setup

/// <summary>
/// The delegate that is going to be used.
/// </summary>
private Action OnGUIMethod;

/// <summary>
/// The standard GUI method, as inherited by MonoBehaviour.
/// </summary>
private void OnGUI () 
{
    if (OnGUIMethod != null) {
        OnGUIMethod();
    }
}

/// <summary>
/// Define what screen to show first.
/// </summary>
private void Start () {
    OnGUIMethod = Screen1;
}

#endregion

#region Screens

/// <summary>
/// A very simple function that will theoretically show two buttons,
/// which in turn show the other screens. The following functions
/// work similarly.
/// </summary>
private void Screen1 () {
    // Show all that appears on the first screen – some Buttons might do

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen2;
    }

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen3;
    }

}

private void Screen2 () {
    // Show all that appears on the second screen – some Buttons might do

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen3;
    }

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen1;
    }
}

private void Screen3 () {
    // Show all that appears on the third screen – some Buttons might do

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen2;
    }

    if (GUI.Button(/* GUI.Button stuff comes here */)) {
        // Do stuff here
        OnGUIMethod = Screen1;
    }
}

#endregion

}

Of course, using the coroutine pattern shown here, you could also add your own fade-ins and -outs here.

/