Allowing only one toggle to be on

Hi, all!

I’m currently working on a project where im instantiating toggle buttons. I want to allow the user to select only one of those buttons. Is there any way to check if there is a toggled button already so i could disable the rest?

Thanks.

thats what a toggle group is for

https://docs.unity3d.com/Manual/script-ToggleGroup.html

1 Like

Using a ToggleGroup instead of Toggles is the obvious solution. If you can’t use that for some reason though, you can make a manager script that has references to all of the toggles, then simply register for Toggle.onValueChanged on each. A really cute way to do this is to use a lambda, for instance:

public class ToggleManager : MonoBehaviour
{
    [SerializeField]
    protected Toggle[] toggles;

    private void Awake()
    {
        for(int i = 0; i < toggles.Length; i++)
            toggles[i].onValueChanged.AddListener((t) => OnToggleValueChanged(toggles[i], t));
    }

    private void OnToggleValueChanged(Toggle toggle, bool newValue)
    {
        if (newValue)
        {
            for (int i = 0; i < toggles.Length; i++)
            {
                if (toggles[i] != toggle)
                    toggles[i].isOn = false;
            }
        }
    }
}

Note that this will recursively trigger OnToggleValueChanged while you’re changing values- that’s why it’s very important to only bother changing anything if the new value is true, so you don’t infinitely loop.

Hi, all!

Thanks for all the help! I used a toggle group but I assigned the group via script for the prefab.

Hi all,
thought id post my method of solving this problem without code and using the toggle group. within the on value changed in each toggle other than the selected use the static parameter isOn and set it to false. Add the selected toggle and use the dynamic parameter isOn