My game contains about 500 trees (my own preFabs, not Unity trees) each of which Instantiate()s an enemy every few minutes or so. After about 40 enemies have been spawned, the game slows considerably, and gets worse from there. This isn’t to do with the enemies, btw-- if I simply place several few hundred enemies into the scene everything works fine, so it must be this script.
This is the script on the tree. As you can see, it’s very sparse, not sure what’s slowing the game down. I also don’t know why the number of enemies would make this script slower, since it doesn’t store them… Thoughts?
public GameObject creature;
public Vector3 displacement = new Vector3(0,0,0);
public float spawnPeriod = 300.0f;
public float firstSpawnPeriod;
bool readyToSpawn = true;
bool first;
void Start()
{
first = true;
firstSpawnPeriod = Random.Range(2.0f, spawnPeriod);
}
void Update ()
{
if (readyToSpawn)
{
Spawn();
StartCoroutine(Delay());
}
}
IEnumerator Delay()
{
if (first)
{
readyToSpawn = false;
yield return new WaitForSeconds(firstSpawnPeriod);
readyToSpawn = true;
first = false;
}
else
{
readyToSpawn = false;
yield return new WaitForSeconds(spawnPeriod);
readyToSpawn = true;
}
}
void Spawn()
{
Instantiate(creature, transform.position+displacement, transform.rotation);
}