- Home /
Question by
jb777 · Sep 07, 2011 at 11:30 PM ·
gameobjectforeach
foreach loop with an array of GameObjects
I'm not sure what I am doing wrong
error CS0030: Cannot convert type UnityEngine.GameObject' to
int'
Code:
public GameObject[] enemies; //dragged 6 GameObjects into Inspector
void OnTriggerEnter(Collider collider)
{
//activate enemies
foreach (int i in enemies) //the line the error is pointing to
{
//enemies[i].active = true;
}
}
Comment
Best Answer
Answer by aldonaletto · Sep 07, 2011 at 11:39 PM
The right way to do it is:
void OnTriggerEnter(Collider collider) { //activate enemies foreach (GameObject enemy in enemies) { enemy.active = true; } }The instruction foreach loops through all elements in the group using internal pointers or indexes; you just supply a variable of the correct type, and foreach assigns to it a new element each iteration.
Thanks. Never got the hang of foreach statements but now I think I know what they are about.
Answer by RubikAdams · Dec 11, 2019 at 02:21 PM
Actualization to 2019
void OnTriggerEnter(Collider collider)
{
//activate enemies
foreach (GameObject enemy in enemies)
{
enemy.SetActive(true);
}
}
Your answer
