Help With "For Loop" Not Working?

I have a “for loop” which I want to execute the code inside every time a “SpiderAmount” is added. Here it is:

for (var i = 0; i < SpiderAmount; ++i)
{
    Instantiate (spiderPrefab, Vector3 (2.0, 0, 0), Quaternion.identity);
    print (i);
}

I put it in an “Update function” and it printed i forever and kept on printing. It printed 0, 1, 0, 1 constantly. I must be doing something wrong, do you know what?

Well, by virtue of being in the Update function, it means you’re running it every frame. So, every frame you’re spawning (for now) two spiders.

Shouldn’t you have some condition that causes this to happen? Like a timer or a collision?

Try adding one line inside your for loop if you want to do it this way:

for (var i = 0; i < SpiderAmount; ++i)
{
    Instantiate (spiderPrefab, Vector3 (2.0, 0, 0), Quaternion.identity);
    print (i);
    SpiderAmount--; // Reduce the amount since we just spawned a spider.
}

There are definitely different approaches, but this should fix your for loop.