Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to get the number of items in an array (C#)

Discussion in 'Scripting' started by Lenticularic, Jul 18, 2021.

  1. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    I'm trying to make a system that lets you beat the level after you kill all the enemies, but I can't b/c I don't know how to get the number of items in an array

    here's what I'm planning
    Code (CSharp):
    1. using UnityEngine.SceneManagement;
    2. using UnityEngine;
    3.  
    4. public class DeathManager : MonoBehaviour
    5. {
    6.     bool isNull;
    7.     GameObject[] enemies;
    8.     void Start() {
    9.         enemies = GameObject.FindGameObjectsWithTag("Enemy");
    10.     }
    11.     void Update() {
    12.         if(/*checking how many items are in the array*/) {
    13.             //doing something based off that
    14.         }  
    15.     }
    16. }
    17.  
     
  2. TheFunnySide

    TheFunnySide

    Joined:
    Nov 17, 2018
    Posts:
    192
    With Arrays you can use .Length
    Lists have .Count

    The enemies array you have is created once and wont change when you kill enemies though.

    You might want to recalculate this array every frame (which is horrible btw).
    Better solution is to use a List instead of Array and have the enemies remove themself then they die.
     
    Lenticularic and PraetorBlue like this.
  3. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    I've never used lists before, how do you make list and add things to them?
     
  4. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
  5. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    how do you add and remove game objects, I'm trying to add all game objects with the tag enemies but I can't since that's an array. But if I make it a list of arrays I can't remove the dead enemies.

    Code (CSharp):
    1. using UnityEngine.SceneManagement;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DeathManager : MonoBehaviour
    6. {
    7.     bool isNull;
    8.     public List<GameObject> enemies = new List<GameObject>();
    9.     void Start() {
    10.         enemies.Add(GameObject.FindGameObjectsWithTag("Enemy"));
    11.     }
    12.     void Update() {
    13.         if(enemies.Count == 0) {
    14.             //doing something based off that
    15.         }  
    16.     }
    17. }
    18.  
     
  6. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590