- Home /
for each element in an array
I am reading a tutorial with the following:
for (var hit in colliders)
This appears to be like a for each element in an array. Is that what this line is doing? Is it looking up the total number of elements in the array colliders[] and assigning that value to the variable hit? If so, is hit an int?
Thanks
Answer by dhendrix · Jun 10, 2010 at 05:47 PM
That code in of itself does nothing, it is just looping through the array called colliders (which I'm assuming is a group of colliders). You need code in brackets after that statement in order to put it to use.
for (var hit in colliders)
{
hit.SendMessage("DoDamage");
}
That code will loop through every object in the array called colliders, and you can refer to each object individually with the new var called hit, and call SendMessage on each one.
To answer your other question, no hit is not an int, it is the same type of whatever kind of objects is in the array called colliders. You may be use to using ints to refer to array indexes, but using this method indexes are no longer necessary.
Sometimes you will of course need to use the old method of for looping so you can track which index you are on and use that int index for other things (like referring to other arrays).
Answer by Jeff Ciaccio · Jun 10, 2010 at 05:39 PM
I found the following on w3schools
JavaScript For...In Statement The for...in statement loops through the elements of an array or through the properties of an object.
Syntax for (variable in object) { code to be executed } Looks like this is what's happening in script above. Can anybody confirm?
Answer by Eric5h5 · Jun 10, 2010 at 05:55 PM
for (collider in colliders) {
print (collider.bounds);
}
gets the same results as
for (i = 0; i < colliders.Length; i++) {
print (colliders[i].bounds);
}
In the case of the for/in loop, the "collider" variable is local to that loop only and doesn't exist outside it. The second loop doesn't allocate any additional variables.
I think i is an additional int variable, surely more lightweigt than the collider variable. Thanks for the excellent post !
Your answer
Follow this Question
Related Questions
How to store gameobjects in an array 2 Answers
Convert Array to String 3 Answers
How can I make an NPC follow a path specified by an array? 0 Answers
Naming array elements 1 Answer
Simple Looping drag and drop game 1 Answer