When I run the game, a infinite loop occurs and Unity freezes

I can’t create a spawn system that works properly. When I run the game, a infinite loop occurs and Unity freezes.

Pls help

public float SpawnTime;
public GameObject enemy;
public float minZ = -2.455f;
public float maxZ = 1.499f;
public Transform spawnPoint;

int infiniteAvoid = 0;
private void Start()
{
    SpawnTime = 4f;
}

void Awake()
{
    StartCoroutine(RandomSpawn());
}

IEnumerator RandomSpawn()
{
        //Spawn
        //if (infiniteAvoid >= 1000) break;
        GameObject clone = Instantiate(enemy, new Vector3(spawnPoint.position.x, spawnPoint.position.y, Random.Range(minZ, maxZ)), Quaternion.identity);

        yield return new WaitForSeconds(SpawnTime);
        infiniteAvoid++;
}

2 Answers

2

There is no loop in your coroutine, so it is only going to run once. Is this script attached to the enemy object that you are instantiating in the RandomSpawn routine? If so, then each enemy that spawns will immediately spawn another enemy which could cause an infinite loop.

You have to call StartCoroutine() after you set the SpawnTime and you’re doing the opposite here as Awake() is always called before the Start() method!