- Home /
Trying to get enemies to stop spawning when player is destoryed
OK so I got my enemies to spawn from several spawn points but I can't seem to figure out how to make them stop when the player is destroyed. Pretty sure I don't know how cancelinvoke works.
public class GameController : MonoBehaviour { public GameObject slayer; public GameObject enemy; public float spawnTime = 3f; public Transform[] spawnPoints;
void Update() {
if (GameObject.FindGameObjectsWithTag("Player") == null)
CancelInvoke("Spawn");
}
void Start ()
{
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
}
Answer by karljj1 · Apr 26, 2015 at 09:26 PM
FindGameObjectsWithTag will return an empty array when the player is destroyed, not null. So check the length of the array instead of checking for null.
if (GameObject.FindGameObjectsWithTag("Player").Length == 0)
Also its worth pointing out that this is not a very efficient way to do things. Your searching for the player every frame, why not cache the player GameObject the first time you find it and then simply check if its null each frame.
Like so:
GameObject player;
void Start ()
{
player = GameObject.FindGameObjectsWithTag("Player")[0]; // Assuming there is only one player
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Update() {
if (player == null)
CancelInvoke("Spawn");
}
Be sure to mark the answer as correct if it worked for you. :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Enemy Spawner help 1 Answer
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer