- Home /
how to index through game objects?
GameObject[] bullets = GameObject.FindGameObjectsWithTag("bullet");
if (transform.position.x == bullets[i].transform.position.x){
transform.Translate(Vector3.right * Speed * Time.deltaTime);
i++;
}
i want to be able to check the npc's position relative to the bullets' position and since there's multiple bullets I need to index them but I don't know why this code isnt working. Or if theres a better way to do this without having to put all the bullets into the array. the code is way more complex than this and theres a lot more conditions but I just need to know how to index through all the bullets correctly.
Is there anything I have to do when I initiate the bullet initially?
Answer by LemonLake · Aug 26, 2013 at 04:50 PM
You're only looking at one bullet. Try using a while loop or a for loop. C#:
for(int i = 0; i < bullets.Length;i++){
if (transform.position.x == bullets[i].transform.position.x){
transform.Translate(Vector3.right * Speed * Time.deltaTime);
}
}
JS:
for (var i = 0;i < bullets.length;i++){
if (transform.position.x == bullets[i].transform.position.x){
transform.Translate(Vector3.right * Speed * Time.deltaTime);
}
}
not getting any errors now but the code still isn't working. Is there anything I need to do when I initiate the bullet? Like use code to add it to the puffs[] array? It's in a separate script so how would I do that