loop causes freeze
in this code i spawn in an enemy in random positions across the map. i have recently added a loop so that i can only create 50 enemy but as soon as the counter reaches 50 it freezes.
could some one please fix this or show me another way to limit the amount of enemy's that spawn
//Array of enemies to spawn public GameObject[] wanderer;
//Enemies will be spawned in random positions inside these boundaries
//The minimum x and z position to spawn the enemies
public Vector2 minSpawnPos;
//The maximum x and z position to spawn the enemies
public Vector2 maxSpawnPos;
//The time between enemy spawns
public float spawnRate = 3f;
//The minimum distance to spawn the last spawned enemy
public float minSpawnDistance = 2f;
Vector3 lastSpawnPosition;
float lastSpawn;
[SerializeField] int wandererCount = 0;
private void Start()
{
}
private void Update()
{
//Time check to see if it's time to spawn a new enemy
if (lastSpawn + spawnRate < Time.time)
{
do
{
SpawnWanderer();
} while (wandererCount > 50) ;
}
}
private void SpawnWanderer()
{
Vector3 spawnPosition;
//Selects a random enemy to spawn from the array of enemies
int enemySpawnIndex = Random.Range(0, wanderer.Length);
//Will keep on generating a new spawn position until it's far enough away from the last one
do
{
spawnPosition = new Vector3(Random.Range(minSpawnPos.x, maxSpawnPos.x), Random.Range(minSpawnPos.y, maxSpawnPos.y));
} while (Vector3.Distance(spawnPosition, lastSpawnPosition) < minSpawnDistance);
//Spawns a new instance of an enemy
GameObject instance = Instantiate(wanderer[enemySpawnIndex], spawnPosition, Quaternion.identity);
//"Resets" the spawn timer
lastSpawn = Time.time;
//Sets this enemies position as the last spawned enemy
lastSpawnPosition = spawnPosition;
wandererCount++;
}
Comment