Loading lessons...
IMGUI - Legacy GUI Scripting
IMGUI - Legacy GUI Scripting
Immediate Mode GUI (IMGUI) is a code-driven UI system used inside the OnGUI() callback. It is primarily used for custom Editor tools, debug displays, and inspector customization.
The Immediate Mode Loop
Unlike canvas-based UI systems, IMGUI elements are declared and processed on the fly during the OnGUI() rendering loop:
using UnityEngine;
public class DebugPanel : MonoBehaviour
{
private bool _showDebug = true;
void OnGUI()
{
// Renders a checkbox. Toggles the boolean state immediately.
_showDebug = GUI.Toggle(new Rect(10, 10, 150, 20), _showDebug, "Show Debug Details");
if (_showDebug)
{
// Simple text box container
GUI.Box(new Rect(10, 40, 200, 70), "Debug Info");
GUI.Label(new Rect(20, 60, 180, 20), "FPS: " + (1f / Time.smoothDeltaTime).ToString("F0"));
}
}
}
Automatic Layout (GUILayout)
Instead of manually calculating pixel positions (Rect), use GUILayout to automatically calculate sizes:
void OnGUI()
{
GUILayout.BeginVertical("box");
GUILayout.Label("Editor Options");
if (GUILayout.Button("Reset Scene"))
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
GUILayout.EndVertical();
}
Styles and Skins
Customize IMGUI fonts, margins, and states with GUIStyle and GUISkin structures:
public GUIStyle customStyle;
void OnGUI()
{
GUILayout.Label("Custom Red Warning Text", customStyle);
}
TL;DR
- IMGUI UI runs in the
OnGUI()callback. - GUI requires manual
Rectdimensions;GUILayouthandles sizing automatically. - Excellent for Editor scripting and debug panels; not recommended for in-game HUDs.