If Statement - if all UI.Toggles in an array are true or false - how to implement

Hi All

I’m trying to figure out how to structure an if statement to deal with an array of an indeterminate length.

Say I have an array that holds a number of Toggles. This array doesn’t have a set size - it is case specific so could be anything (although it will likely have a length of between 1 and 10).

I would like to have a If statement that says ‘if ALL Toggles in the array are TRUE, do this’, and ‘if ALL toggles in the array are FALSE, do this’.

There’s no situation where I will need to do something based on some being on and some being off - only two statements; one with all on, and one with all off.

Can anyone help with this? I’m not too sure how to tackle it. I could hard code the array items [0, 1, 2] etc up to a safe number but I would like to keep it generic - something that could work with even a thousand Toggles if necessary.

Thanks

Loop through the array, pseudocode:

var allTogglesOn = true
for (i in array)
    if (i == false)
        allTogglesOn = false
        break

–Eric

1 Like

I am away from my unity computer so this might not be perfect but, if you use linq and c# you can do this quite easily:

List<Toggle> toggleList = ....
    int onCount = toggleList.Where(n => n.isOn == true).Count();
        if( onCount == 0)
        {
            // all toggles are off OR the list is empty
        }
        else if( onCount == toggleList.Count)
        {
            // all toggles are on
        }

Please correct me if i am wrong though.

toggles.All(toggle => toggle.on)
toggles.All(toggle => toggle.off)

Thanks so much everyone, I’m away from my PC for a few days but I can’t wait to get stuck into these when I return!