Get the FULL version

Unity: GUI Toggle Pair

Unity: GUI Toggle Pair thumbnail

This new (and brief) Unity programming post explains how to create a pair of GUI.Toggles that modifies the value of a single boolean. This means that, when one toggle is selected, the other one should be automatically set to unselected. This is best explained with an example, which can downloaded at the end of the post.

In this example, the value of the boolean day will be set using two toggles. When the toggle “Day” is selected, the “Night” toggle should be unselected. This must also work on the other way around, like this:

In this image, the day boolean is set to true.

In this example, the day boolean is set to true.

At the above image, the day boolean is set to false.

At the above image, the day boolean is set to false.

To make the day boolean value be set by both toggles, one toggle should return the inverse of the value of the boolean the other toggle has just set. Here’s the code:

using UnityEngine;
using System.Collections;

public class TogglePair : MonoBehaviour 
	//Create and initialize a boolean to be toggled
	private bool day = true;

	void OnGUI()
		//Render the toggle normally = GUILayout.Toggle(,"Day");
		/* Invert the boolean value and return the inverse of 
		 * what has been set on the toggle.*/ = !GUILayout.Toggle(!,"Night");

		//Render the selected value.
		GUILayout.Label("Day is: " +;

The code should be self explanatory. Basically, the boolean day is created and initialized (line 7). Then, the first toggle is rendered, just as described on the official documentation (line 12). The second toggle, the one labeled “Night”, is rendered just as the previous one, but with a couple of differences.

The inverted (note the ! sign) value of the day boolean is passed as the first parameter to the GUILayout.Toggle() method. This makes the toggle render the correct state, which is the inverse of the day variable value. Additionally, the value of the boolean returned by the GUILayout.Toggle() method is inverted (again, notice the ! sign). It makes the GUILayout.Toggle() method return the correct boolean value, which is stored in the day boolean. In other words, when the “Night” toggle is selected, the day should be set to false.

That’s it! Both JavaScript and C# versions of this script can be found at the example project:


Be the first to leave a comment!

Leave a Comment

Post Comments RSS