Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Open door when array is empty

Discussion in 'Editor & General Support' started by VascoCorreia, May 23, 2021.

  1. VascoCorreia

    VascoCorreia

    Joined:
    Dec 5, 2020
    Posts:
    23
    Like the title says I am trying to make a door that opens when all elements of an array of enemies are empty/null.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DoorScript : MonoBehaviour
    6. {
    7.  
    8.     public GameObject[] enemies;
    9.  
    10.     private bool enemiesCleared;
    11.     private bool switchesCleared;
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.         if (enemies.Length == 0)
    17.             enemiesCleared = true;
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void LateUpdate()
    22.     {
    23.         int enemiesAliveCount = 0;
    24.  
    25.         for (var i = 0; i < enemies.Length; i++)
    26.         {
    27.             if (enemies[i] != null)
    28.             {
    29.                 enemiesAliveCount++;
    30.             }
    31.             if (enemiesAliveCount == 0) enemiesCleared = true;
    32.         }
    33.  
    34.         if (enemiesCleared)
    35.         {
    36.            OpenDoor(gameObject);
    37.         }
    38.  
    39.     }
    40.  
    41.     public void OpenDoor(GameObject door)
    42.     {
    43.  
    44.         door.SetActive(false);
    45.  
    46.     }
    47.  
    48.     public void CloseDoor(GameObject door)
    49.     {
    50.  
    51.         door.SetActive(true);
    52.     }
    53.  
    54.  
    55. }
    I drag my enemy's objects to the array in the inspector.

    It works fine AS LONG as I don't kill the enemy that was assigned to the first index of the array.
    As soon as I kill the enemy assigned to the first index the door opens. Even if there are other enemies alive.

    What am I missing here? I cannot seem to find the error in the logic and why it behaves like that.
     
  2. Delete the 31th line and replace the 34th line with this
    if (enemiesAliveCount == 0)
    and you can get rid of the
    enemiesCleared
    variable too. Unless you use it somewhere else too, in that case just update it inside the if. Also if you do not need how many enemies are alive anywhere, you can put a
    break;
    command after the
    enemiesAliveCount++;