Getting an array of gameobjects with a certain tag
I'm making a game that's similar to Binding of Isaac. There's a room with 4 doors and I want the doors to open after all the enemies are dead. I tried this code
using UnityEngine;
using System.Collections;
public class DoorOpen : MonoBehaviour {
GameObject[] enemies = (GameObject[])GameObject.FindGameObjectsWithTag("Enemy01");
void Update () {
if (enemies.Length == 0) {
Destroy (this.gameObject);
}
}
}
but I get an error that says "NullReferenceException: Object reference not set to an instance of an object". What did I do wrong?
enemies.Length will only be 0 if it hasn't found any objects, which means it will actually be null! so maybe do:
if (enemies == null || enemies.Length == 0) {
This seems like it did something, however now the gameObject gets destroyed as soon as I play the scene. I think it doesn't even create the array with the gameObjects which is very confusing.
Correct, you need to assign enemies in a method, try doing it in Start:
void Start(){
GameObject[] enemies = (GameObject[])GameObject.FindGameObjectsWithTag("Enemy01");
}
Your answer
Follow this Question
Related Questions
Switching the index of a GameObject Array type? 2 Answers
Position Array Returning null reference 1 Answer
How can I get a reference to a Prefab in the Asset folder without instantiating it? 2 Answers
How to get children of a given an array of gameobjects? 1 Answer
How do you order an array by numbers held in Game Object String 0 Answers