I'm creating an enemy spawner in Unity (2D). At long last, I have something that is quite close to working, but the problem is that I want it to destroy all instances of the enemy when the player can no longer see the spawn area.
That is, the player happens upon the spawn area to find several enemies, but if they move so that the camera can no longer see the spawn area, I want those enemies to be deleted and then a different set of the same enemies to be instantiated when the player (camera) happens upon the spawn area again. But when I attempt this initial delete, the script component no longer has an object to instantiate when the player returns.
Here's a snippet of what I have:
if (!notOnScreen && spawned == false)
{
int numberOfEnemies = Random.Range(1, enemyMax);
for (int i = 1; i <= numberOfEnemies; i++)
{
spawnX = Random.Range(minX + 1, maxX - 1);
spawnY = Random.Range(minY + 1, maxY - 1);
Vector3 spawnpoint = new Vector3 (spawnX, spawnY, 0);
if (enemies.Length == 1) {
typeOfEnemy = 0;
}
else if (enemies.Length > 1) {
typeOfEnemy = Random.Range(0, enemies.Length);
}
else {
typeOfEnemy = -1;
}
Instantiate(enemies[typeOfEnemy], spawnpoint, Quaternion.identity);
}
spawned = true;
}
if (notOnScreen) {
spawned = false;
currentEnemies = GameObject.FindGameObjectsWithTag("Enemy");
for (int i = 0; i <= currentEnemies.Length; i++) {
Destroy(currentEnemies[i]);
}
}
}
}
I'm sure there's a way to preserve an instance of the enemy so that they can be instantiated again later, but I'm not sure how (sorry--very new to this). I thought about cheating and having one enemy remain at a different z coordinate behind the map (as this is a 2D game), but that doesn't seem like an appropriate solution. Any thoughts or advice?
(!notOnScreen)
is much more confusing than(!onScreen)
. Also you're using the boolean comparison!
and then right next to that doing a== false
comparison. I would recommend doingif (!onScreen && !spawned)
. Also, you're starting your iteration in your first for loop with i = 1, but doing <= numberOfEnemies, which may result in you spawning one too few enemies. \$\endgroup\$spawned
and move it outside of all of this code and end withspawned = !notOnScreen
, or preferablyspawned = onScreen
. \$\endgroup\$