How to create dynamic array of type GameObject using javascript?

Hi everyone, i have just started the work before a week in unity3d to make my first game. I’m using javascript. i know my question is asked so many time.

My concept is kick a ball to selected target like penalty shoot out. I tried so many references to solve my problem but bad luck :frowning:

I have a fixed number of targets i.e. 6. and created an array of target in the script.

var targets : GameObject[];

and filling array in start() by

targets = GameObject.FindGameObjectsWithTag("Target");

Also removing/destroying the target object when ball hits target

function OnTriggerEnter(collider : Collider) 
{
	if (collider.transform.name == "Ball") 
	{
		Destroy(gameObject);
        }
}

My problem is that when i select the another target it’s giving me following error.

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

i think my array is not dynamic. I’m also not able to add/remove any object runtime from array. how can i do it? Please suggest me. Please provide me some detail what i’m doing wrong?

A “dynamic array” is called a List. But that isn’t your problem here. Your problem is probably elsewhere in code that you didn’t post; where you select a target, you’re not selecting the target you think you are selecting.

You can say for example " targets[4] = null;", or “targets [2] = hit.transform.gameObject” and it will work.

Also, you can not destroy the game object, but instead use SetActive (false). This will get rid of the MissingReferenceException compile error but not the design error that caused it.

I’m not sure if it helps, but I know that in c# you can make a List instead of an array, which is more or less dynamic.

However. This doesnt really seem to be your problem. It seems you’re trying to edit or read some data from your array of gameObjects with the tag “Targets” and you’ve deleted some of the targets from the scene. The script attempts to access a destroyed object, which is no longer there. This can be overcome by making a new function that is run whenever the object gets destroyed. It should look something like this:

function dyingTarget(GameObject dyingObject)
{
  targets = GameObject.FindGameObjectsWithTag("Target");
  GameObject[] newTargets = new GameObject[targets.length - 1]; //sry for C#
  for(var i = 0; i < newTargets.length; i++)
  {
    if(obj.GetInstanceID() != dyingObject.GetInstanceID())
    {
      newTargets *= obj;*

}
}
}