Spawner within range
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);
}
}
Answer by Hellium · Nov 29, 2020 at 03:41 PM
GameObject enemyToSpawn;
Transform enemyParent;
float spawnTime = 2f;
Transform target;
float targetDistance;
float spawnRange = 10f;
float nextSpawnTime = 0;
void Update()
{
targetDistance = Vector3.Distance(target.transform.position, gameObject.transform.position);
if (targetDistance <= spawnRange && Time.time > nextSpawnTime)
{
SpawnEnemy();
}
}
void SpawnEnemy()
{
var enemyWave = Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
enemyWave.transform.parent = enemyParent;
nextSpawnTime = Time.time + spawnTime;
}
Almost perfect, and very quick response. Only issue is that when I enter the spawner's range it sends a burst of 3-5 enemies before it starts following my "spawnTime" float
You may have attached the script multiple times then.
In SpawnEnemy
, add Debug.Log(gameObject.name + " has spawned enemy", gameObject);
and click on the messages to see which gameObject spawned the enemy
Only one copy of the script on the spawner, is it possible that by entering range there's a moment where I'm half in range and it's causing it to double process?
$$anonymous$$y bad, I fixed the code. Only the last line of SpawnEnemy
has changed.
Perfect. Works like a charm. $$anonymous$$uch appreciated!