how to check if all object in my array are destroyed (C#)

Hello
Could someone help me? I want to check if all object in my array are destroyed and when all of them are destroyed do something. I saw the answer for JS but I need C#. Please :slight_smile:

Here you go:

if(whateverArrayYouAreChecking.Length < 1)
		{
			DomSomething();
		}

Thank you for the answer but it does not work for me. For example I have two object in my array, when I destroy both of them nothing is happened

if (miniBosses.Length < 1) { gameController.BossIsDead(); Destroy(gameObject); }

You could try an ObservableCollection with a test for the size of the array.

Note: Needs .Net 4.+ enabled in your player settings


2


Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

public class DoWork : MonoBehaviour {

	public ObservableCollection<int> Ids = new ObservableCollection<int>
	{
		0, 1, 2, 3, 4, 5
	};

	// Use this for initialization
	void Start () {
		Ids.CollectionChanged += OnCollectionChanged;
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Space))
		{
			if(Ids.Count > 0)
			{
				Ids.RemoveAt(Ids.Count-1);
				Debug.Log($"ArraySize: {Ids.Count}");
			}
		}
	}

	void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
	{
		if(Ids.Count == 0)
		{
			DoSomething();
		}
	}

	void DoSomething()
	{
		Debug.Log("Empty Array");
	}
}

EDIT:

The solution you requested in the comments is really terrible code/ badly written, poorly optimised but if you were going down that route.

Just remove items from the collection when you destroy them and then check the collection size instead. i.e.

List<MyObject> MyObjects = new List<MyObject>();

void Update() 
{
    if(MyObjects.Count == 0) DoSomething();
}

void Destroy(index: int) {
    if(index < MyObjects.Count)
    {
        MyObjects.RemoveAt(index);
    }
}

void  DoSomething() 
{
    // CODE GOES HERE
}

Note that this is not as efficient as the first example code as you are constantly checking for the state of the collection on every frame.

I have found the easiest way for my special case :slight_smile:

 if (GameObject.FindGameObjectWithTag("Enemy") == null)

So there was no need in array at all