For loop instantiates object endlessly
so im still really new to unity c# and ive been trying to spawn in 5 squares with a for loop in random areas and for some reason, it just spawns and endless amount and causes major freezing.
public GameObject box;
public int numberToSpawn = 5;
void Start()
{
for (int i = 0; i < numberToSpawn; i++)
{
Vector3 randomPos = new Vector3(Random.Range(-5, 5), (Random.Range(4, -4)), 0);
Instantiate(box, randomPos, Quaternion.identity);
}
}
ive also tried just having the squares spawn to Vector3.zero but still the exact same issue with it spawning endlessly. ive even compared my loop to others and still cannot see a problem. its probably something extremely obvious but i just cant see it.
What is the actual value of numberToSpawn
in the inspector?
Its 5 aswell. I just set it here to be explicit and I've even tried without a variable and with static numbers and its the same result
Which object is referenced in box
? Does the object referenced in box
have this same script attached? If so, you're creating an infinite loop of instantiated objects instantiating object instantiating objects, and so on.
Your answer
![](https://koobas.hobune.stream/wayback/20220613045435im_/https://answers.unity.com/themes/thub/images/avi.jpg)