3

I am making a 2d game in unity. I am using the UI toggle methods and wish to make one of those turn off when the other one is turned on. The method I have tried is doing the following code below (InfiniteMode and CampaignMode are the names of the two toggles):

if (InfiniteMode.isOn)
    {
        PlayInfinite();
        CampaignMode.onValueChanged.Invoke(false);
    }

    if (CampaignMode.isOn)
    {
        PlayCampaign();
        InfiniteMode.onValueChanged.Invoke(false);
    }

Any help for what I can do to achieve this would be great.

Catty01
  • 147
  • 2
  • 9
  • 1
    Have you tried to replace `InfiniteMode.onValueChanged.Invoke(false)` by `InfinteMode.isOn = false`? – derHugo Jan 13 '21 at 13:44

2 Answers2

4

As far as I understand you want to have two UI Toggles which acts as a group, when one of them is on, the rest of the items are off. In order to do this you can use Toggle Group component from Unity UI. You can find more information on that here: Toggle Group documentation.

If you look at Toggle component there is a Group variable. If you create an empty GameObject inside your Canvas and add Toggle Group component to it and assign that Toggle Group object to all your Toggle's which you want to be a part of that group it should work.

hardartcore
  • 16,886
  • 12
  • 75
  • 101
0

You can add listeners to your toggles like this:

[SerializeField]
private Toggle myToggleVar;

private void Start() {
    // UI event listeners
    myToggleVar.onValueChanged.AddListener(delegate { onToggleExec(); });
}

private void onToggleExec() {
    Debug.Log("Toggled!") //here you need to manipulate your other toggle
}
rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47