- Home /
Change global state in list
public enum MyState
{
A,B,C
}
public class ABC
{
int length;
}
public List<ABC> abcs = new List<ABC>();
public MyState state = MyState.A;
void Start()
{
for(int i = 0 i < 5;i++)
{
ABC temp = new ABC();
tmp.length = 1 + i;
abcs.add(temp);
}
}
void Update(){
foreach(ABC a in abcs)
{
if(a.length == 1)
state = MyState.B;
}
}
I want to change my custom enum when one is satisfy my condition in collection. But only last one in collection will do , how to solve it ?
Thanks in advance.
What is ABC and abcs?
I'm having trouble understanding your question.
Answer by ArkaneX · Sep 22, 2013 at 11:48 AM
You have to do
foreach(ABC a in abcs)
{
if(a.length == 1)
{
state = MyState.B;
break; // this causes foreach loop to stop and not check other ABC elements 'length' field
}
}
You could also use LINQ for this (requires using System.Linq;
) and just write
if(abcs.Any(a => a.length == 1))
{
state = MyState.B;
}
I tried first method , It became only first one in list can change state..
$$anonymous$$aybe you didn't add curly brackets under if? Please note, that in your code only one command is executed after if. In my code, there are two commands, so they have to be wrapped in curly brackets.
How did you test it then? If you have a list with two elements, where length of first is 2 and length of second is 1, then does your foreach loop breaks before reaching the second one???
I think he needs to iterate the abcs in reverse. Possibly only if (abcs[abcs.Count-1].length == 1).