OnGUI() Function in Unity

Notes:

OnGUI() Function in Unity:

6. Continuously frame gets updated and rendered

OnGUI method:
- is called many times per frame

- is best for drawing GUI elements and handling GUI events

Ex: Drawing a UI button, handling click event etc.

Example code:

void OnGUI()
{
Debug.Log ("OnGUI");

bool isButtonClicked = GUI.Button (new Rect (0f, 0f, 100f, 30f), "Button");

if (isButtonClicked)
{
Debug.Log ("isButtonClicked" + isButtonClicked);
}
}

Note: For drawing UI elements and handling UI events, it is recommended to use new UI system with Canvas instead of OnGUI event method; because OnGUI is old way of creating UI for games; new UI system with Canvas is more easier, flexible, feature rich and development friendly. OnGUI is code based and new UI system is graphics based.