I have added doors into my game, which I want to open once all of the enemies within a room have been killed.
When an enemy is killed, they are destroyed, so I tried the following -
public GameObject[] enemy;
public bool isDone = false;
void Update ()
{
if(enemy == null && isDone == false)
{
isDone == true;
//Opening the door()
}
}
When an enemy is destroyed, they are classed as missing on the doors inspector. When all of the enemies are missing, I had hoped that == null would be called, but it is not.
Could someone tell me whatâs wrong with the script?
Yes, one equals too many way used, however I this is a red herring. I will remove that from the below example. The bool of isDone is not relevant, enemy == null is never called.
The enemy is within an array list, I feel this is why I am having problems. Once an enemy is destroyed, they are given a missing reference, how do I look for all of the references to be missing? If I could ask âif (enemy == missing stuffâ, then it would be called.
Yea first you should do isDone = true;
2nd, if you destroy an enemy with Destroy() doesnât mean that the array will be null at the end. just the element in this array will be null.
public GameObject[] enemy;
public bool isDone= false;
void Update () {
if(CheckIfAllEnemyDead() && isDone == false) {
isDone = true;
//Opening the door()
}
}
bool CheckIfAllEnemyDead() {
for ( int i = 0; i < array.Length; i++) {
if( enemy[i] != null) {
return false;
}
}
return true:
}
Thanks @martinmr , I didnât know that using foreach in Update was a bad idea. I have used your code, but am finding that after each enemy is made null, openDoor() is called. Any idea why?
Note, I kept the for(int i = etc.) as the console didnât accept enemies, enemies[ ]. The ! operator cannot be applied to operand of type âŚGameObject[ ].
I guess keeping for(int i = etc.) is likely the reason why this is not working.
public GameObject[] enemy;
public bool isDone= false;
void Update () {
if(isDone == false && CheckIfAllEnemyDead()) {
isDone = true;
openDoor()
}
}
bool CheckIfAllEnemyDead() {
for ( int i = 0; i < array.Length; i++) {
if( enemy[i] != null) {
return false;
}
}
return true:
}
Checks if all enemys are dead, if just one is alive, it will return false so it even hasnât to go through the rest of the array. If all are dead â null than it will reach the return true.
@kittik yea you are right, my last code posted was opening every time enemy is dead. this should fix it.
If I were to keep going with an approach like this I believe I would store my enemies in a List⌠when they die Iâd remove them. Then just check if the List count > 0.