I tried but couldn't... My code is as follows:
for(int i = 0; i == oList.Count; i )
{
GameObject.Find(oList[a]).GetComponent<Image>().color = GreenCol;
a ;
}
i am getting this error:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <eae584ce26bc40229c1b1aa476bfa589>:0)
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
LevelManager.Update () (at Assets/Scripts/LevelManager.cs:27)
im use unity game engine
CodePudding user response:
The logic is wrong there. Why do you need variable a? I suggest you to try and learn some concepts of programming concepts. Here it is the reworked code:
for(int i = 0; i < oList.Count; i )
{
oList[a].GetComponent<Image>().color = GreenCol;
}
CodePudding user response:
If you iterate over an Array in a for-loop you should also use the i variable you declared in the loop.
Also as the oList.Count returns the size of the array, you start always at 0 as the first Position. So the condition to leave the loop should bei i < oList.Count
as oList.Count -1
is the last Item in your Array.
If your array contains the names of the objects as strings, your code should look like this.
for(int i = 0; i < oList.Count; i )
{
GameObject.Find(oList[i]).GetComponent<Image>().color = GreenCol;
}
If the array contains the GameObjects directly your code should look like in Eduard Hasanaj's answer.