Home > Software design >  Check if all the buttons in an array are active
Check if all the buttons in an array are active

Time:09-22

Is there a way to check if all the buttons in an array are active or not, all at once? I am using for loop to determine it but the break; does not really signify anything that I want to achieve.

public Button[] bts;

public void StateButton()
{
    for (int i = 0; i < bts.Length;   i)
    {
        if (!bts[i].interactable)
        {
            Debug.Log("all buttons are off");
            break;
        }
        else
        {
            Debug.Log("atleast one is on");
        }
    }
}

CodePudding user response:

It is possible using LINQ:

var allInteractable = bts.All(e => e.interactable)

Depending on the length of the array and the expected state of the buttons (i.e. you know that almost all the time at least one button is not interactable) it might be more performant to inverse the query using:

var atLeastOneNonInteractable = bts.Any(e => !e.interactable)

CodePudding user response:

Your debug logs don't really match with the title of your question.

Written out it should either be

public bool StateButton()
{
    var allOn = true;
 
    foreach (var btn in bts)
    {
        if (!btn.interactable)
        {
            allOn = false;
            break;
        }
    }

    Debug.Log(allOn ? "All buttons on" : "At least one button off");
    return allOn;
}

or

public bool StateButton()
{
    var anyOn = false;
 
    foreach (var btn in bts)
    {
        if (btn.interactable)
        {
            anyOn = true;
            break;
        }
    }

    Debug.Log(anyOn ? "At least one button on" : "All buttons off");
    return anyOn;
}

depending on your needs.

And then you already have Michael Mairegger's answer using Linq to shorten this into a single line ;)

  • Related