Hi,
i want to have only one bool in the array to be true and the rest should be false.
The code works for me, but i have 100+ index numbers. Is there a better way?
public bool[] Btn;
int Index;
public void SendEvent()
{
if (Index== 0)
{
Btn[Index] = true;
}
else
{
Btn[Index] = false;
}
if (Index== 1)
{
Btn[Index] = true;
}
else
{
Btn[Index] = false;
}
}
Loop over the array.
for(int i = 0; i < Btn.Length; i++)
{
if (Index == i)
{
Btn[i] = true;
}
else
{
Btn[i] = false;
}
}
We can of course simplify that if statement. I only showed it so you can see the logical trajectory to the final solution from your solution.
for(int i = 0; i < Btn.Length; i++)
{
Btn[i] = (Index == i);
}
When using arrays/collections, the loop should become very familiar with you.
…
I should also point out your original code is going to have a problem in its current state. If Index = 0, then it’s going to set both to false. Since when you get to the second if/else it sets it sets the slot 0 false. I assume you meant to be something like:
if(Index == 1)
{
Btn[1] = true;
}
else
{
Btn[1] = false;
}
1 Like