- Home /
Where should I use a traditional forloop as opposed to 'for (var i in monsters)'?
I'm iterating through an array with a for loop. Here's the code:
for (var i in monsters) {
if(i == monsterName) {
newEnemyName = i;
Debug.Log (i + 1);
}
}
Now, here's the problem: I want to print the variable in the array after the current one. If I do i + 1
like in the code, I just get the output of i (let's say troll) with a one on the end, like this: Troll1. How do I print the variable that comes after i?
Thanks - Elliot "The Question Asker" Bonneville
P.S. I've been struggling with a particularly knotty problem for about two days now, so I've been asking a lot of questions about arrays and forloops. Please forgive me. :)
Answer by Mike 3 · Jul 29, 2010 at 09:28 PM
I think you just want a more traditional for loop:
for(var i = 0; i < monsters.Length; ++i)
{
//do stuff with i (the index) and monsters[i] (the string relating to the index)
}
note - if you do monsters[i+1] now it should work, but be careful about the array bounds with it
By the way, thanks to you, I've solved my problem, and my project is nearing completion.
Just thought I'd throw this out there also. foreach loops will allocate memory if you are looping through a reference type while using a for loop then getting the arrayIndex[i] doesn't. Saves some memory if you are on iPhone.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070046im_/https://answers.unity.com/themes/thub/images/avi.jpg)