My array does not update when object is destroyed. How do I fix it? (java)

The code below is supposed to put all of the “Objectives” into an array and then when all of the “Objectives” are destroyed, destroy the object the code is attached to. Getting the objects in the array works however they do not leave when they are destroyed. Anybody got a fix?

function Start () {
    var gos : GameObject[];
    gos = GameObject.FindGameObjectsWithTag("Objective");

    if (gos.length == 0) 
    {
        Debug.Log("All Points Located");
        Destroy (gameObject);
    }
}

You’re only checking if the length of the array is 0 on the first frame. Make your gos variable a class level variable and move your if statement into the Update() method.

The Start function is called only once at the start of the scene.
In order to have something to be checked every frame you need to use the Update() function instead.

Also GameObject.FindGameObjectsWithTag() gives you a GameObject[]. That is an array of your Objectives but destroying a GameObject wont remove it from this particular Array, thus the array.length wont change. To check how many “Objectives” remain you also need to call this function every frame.

So you can actually put every single lines from your Start() function into the Update() function and it should do the trick.

But GameObject.FindGameObjectsWithTag() is a heavy function and takes too much time to be used each frames. Instead what you could do is have an Objective class that keep a static number of how many objectives there are. You’d put this script on all your objectives :

using UnityEngine;
public class Objective : MonoBehaviour{
	public static int Count { get; private set; }

	void Start()
	{
		Count = Count + 1;
	}

	void OnDestroy()
	{
		Count = Count - 1;
	}
}

And to know if they are all done you just have to do : if(Objective.Count<=0) DoStuff();

This cost fewer memory, processing power and is way more elegant.

(Sorry I don’t know UnityScript so i did it in C#, so you can probably guess what changes. And if you’re starting Unity its better if you use c# instead of javascript there are more plugins/Tutorials/people who use it)