In this recipe, we will show you how toggle buttons for the user interface of games made with Unity can be created and managed.
Like the previous recipe, you must have the Options Screen scene loaded in the Editor and the GUI script open in Monodevelop.
Let's begin by creating a
bool
variable to control whether the toggle is on or off. We do this by adding the following declaration at the top of the script:private bool toggleAudio = true;
Next, we create the toggle button on the screen by adding the following line inside the
OnGUI()
function:toggleAudio = GUI.Toggle(new Rect(100, 30, 10, 10), toggleAudio, "Toggle Audio");
Now, in the
Update()
function, we add a line to ensure that the audio is enabled, depending on thetoggleAudio
value:audio.enabled = toggleAudio;
The following screenshot provides the complete
GUI
script we used for the Options Screen scene: