I’m looking for a way to have a spawner instantiate enemies when the player is in range, and stop spawning when the player leaves that range. I thought a Coroutine would work, but I’m pretty new at it and with a Coroutine it’s just spawning from the beginning. I also haven’t a single clue how I would get it to stop once the player gets out of range. I’ve tried replacing “while (true)” with “while(targetDistance <= spawnRange)” and removing the if statement from my Start, but no dice.
GameObject enemyToSpawn;
Transform enemyParent;
float spawnTime = 2f;
Transform target;
float targetDistance;
float spawnRange = 10f;
void Start()
{
if (targetDistance <= spawnRange)
{
StartCoroutine(SpawnEnemies());
}
}
void Update()
{
targetDistance = Vector3.Distance(target.transform.position, gameObject.transform.position);
}
IEnumerator SpawnEnemies()
{
while (true)
{
var enemyWave = Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
enemyWave.transform.parent = enemyParent;
yield return new WaitForSeconds(spawnTime);
}
}