How is this for loop work? (For loop logic)

Hello,
I don’t understand why the code below works. OK, this is what i want, i want it to work BUT i don’t understand the logic behind it so i am frustrated that i cannot understand it. Here is the code;

function Update()
{
    for(var i : GameObject in GameObject.FindObjectsOfType(GameObject))
    {
        if(i.name.Contains("blabla"))
        {
            Destroy(i);
        }
    }
}

This code destroy all of the gameobjects that contain word blabla which is fine BUT i don’t understand why it doesn’t destroy all of the gameobjects inside i array? In my logic, from my understanding, here is what i expected; for loop creates an array called “i” and adds all of the gameobjects in the scene into that “i” array, after, if statament looks for whether or not “i” array contains gameobjects with a string blabla, so yes in conclusion “i” array has gameobjects with a string blabla and “i” array needs to be destroyed. Lets take an example of bag of balls that contains different colors inside of the bag(red, green, blue). So “i” array is the bag and if statament looks for if the bag contains red balls if so throw the bag into trash can. Hope this helps.

Thank you in advance.

‘i’ is not the array but it is the single gameobject from the array. The actual array is returned by GameObject.FindObjectsOfType(GameObject). Read: [Object.FindObjectsOfType][1]

So in your analogy, GameObject.FindObjectsOfType(GameObject) returns an array which is the bag of balls and i is a single ball from the bag. Now each time in the for loop i contains a ball from the bag and the if statement checks for if the ball is red or not. If red, it deletes it.

This code can be interpreted as in C#:

GameObject[] GOs = GameObject.FindObjectsOfType(GameObject);

for(int i = 0; i < GOs.Length; i++)
{
    if(GOs*.name.Contains("blabla"))*

{
Destroy(Gos*);*
}
}
_*[1]: http://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html*_

You are iterating every gameobject called ‘i’ in the array ‘GameObject.FindObjectsOfType(GameObject)’. Then you check if i.name contains the string you specified. If it contains it then destroys it.

I think you don’t understand the for loop.

“i” is not an array, but it will take at each loop the value of only one game objeect in your scene.

so “i” in your bag example will be firstly the bag witch is not red, and after it will become the blue ball witch is also not red and after it will become the red ball witch is red and destroy it…

I’m working in c# but it seem like a “foreach”.