I have an array of 6 toggle buttons. I want to set this up so that only 1 toggle can be activated at a time. So you click another toggle on, it disables all the others. Right now I’ve done this very manually with some nested for loops that run through and check every toggles state if another toggle is clicked.
Was just curious, is there any more automatic way to do this in the Unity GUI functions? or any more advanced C# functionality that would make this more elegant than just nested for loops?
So after banging my head against the table on this for way longer that I thought it would take, this is what I came up with.
using UnityEngine;
using System.Collections;
public class toggler : MonoBehaviour {
public GUISkin mySkin;
private Rect windowRect = new Rect (20, 20, 120, 200);
//how many Toggles?
public int arraySize = 4;
bool[] node;
void Start()
{
node = new bool[arraySize];
//set all nodes to false
for (int i = 0; i < node.Length; i++)
{
node[i] = false;
}
//except first one because that is where the player starts
node[0] = true;
}
void OnGUI()
{
GUI.skin = mySkin;
GUI.backgroundColor = Color.white;
windowRect = GUI.Window (0, windowRect, WindowFunction, "My Window");
}
void WindowFunction (int windowID)
{
//this bool array is used to retain the bool states before this update
bool[] nodeCurrent = new bool[node.Length];
for (int i = 0; i < node.Length; i++)
{
nodeCurrent[i] = node[i];
//set node equal to the changes in UI AFTER setting nodeCurrent
//equal to node, so that nodeCurrent returns the bool states from LAST update
node[i] = GUI.Toggle(new Rect(10, i * 20, 14, 14), node[i], GUIContent.none);
}
if(GUI.changed)
{
//run through each node
for (int i = 0; i < node.Length; i++)
{
//if node is TRUE, but nodeCurrent, the bool states from LAST update
//are not true, then continue, this is done so that you can tell
//which toggle was set to true this update, and has not been true
//since last update
if(node[i] !nodeCurrent[i])
{
//once true run through every node
for (int i2 = 0; i2 < node.Length; i2++)
{
//and make them false as long as it's not the node that was just toggled on!
if (i2 != i)
{
node[i2] = false;
}
}
}
}
}
GUI.DragWindow (new Rect (0,0, 10000, 20));
}
}
Basically just stick that on your camera, or anything, set the array size equal to however many toggles you want and play, then click a toggle and all other toggles will shut off.
I post this so that, if someone wishes to do something similiar they don’t have to get a headache trying to figure out this really simple funtion. And also, if there is still a more elegant way to do this than the way I’ve done, I would really like to know!
Thanks man. Definitely still needed help on this 10 years after I posted it.
3 Likes