GameObject arrays

Hello! This question has been asked and answered a lot, but I have not been able to use those answers and apply them to my situation…hence I have to go ahead and ask this question yet again.

http://forum.unity3d.com/threads/46032-Array-of-GameObjects-solved

This is the main one I’ve been looking at, but I’ve also been checking out other answers…

Like everyone, I want to add a bunch of GameObjects to an array, in my case I want to do this on a trigger. And the array is a target, where once I press a button I want to be able to destroy the objects in that array, tetris kinda?

public var MultiTarget : GameObject[];	

This is what I’d assume would work as an array that gets filled with GameObjects.

function OnTriggerStay (collider : Collider) {

if (collider.gameObject.tag == "MultiMarker")
        {
            inputscript.MultiTarget.Add(gameObject);
        }    
}

And here is one example of the many ways I’ve tried to work it out. (adding to the collision even hasn’t helped either).

Unity gives me the error:

Cannot convert ‘UnityEngine.GameObject’ to ‘UnityEngine.GameObject’.

So my question is,
how am I to add a bunch of GameObjects (anything from 1-9 or more!) to an array on trigger enter?
And also, how would I go about destroying everything in that array once I input whatever button?

Destroy(SingleTarget);

This is what I use for single targets, easy enough.

Destroy(MultiTarget[]);

Would this just…work?

I hope somebody has an answer (or link!) to this.
the whole new Array(); workflow doesn’t want to work either…
Thank you!

1 Answer

1

You mixed builtin arrays and array class concepts.

For builtin arrays

public var MultiTarget : GameObject[] = new GameObject[100];
private var index : int = 0;

function OnTriggerStay (collider : Collider) {
 
if (collider.gameObject.tag == "MultiMarker") // You also need to check if the array is full
        {
            MultiTarget[index]=collider.gameObject;
            index ++;
        }    
}

For array class:

public var MultiTarget : Array = new Array ();

function OnTriggerStay (collider : Collider) {

if (collider.gameObject.tag == "MultiMarker")
        {
            MultiTarget.Add(collider.gameObject);
        }    
}

for(var target : GameObject in MultiTarget){
Detroy(target);
}

To destroy everything in both, use:

for(var target : GameObject in MultiTarget){
    Destroy(target);
}

Try: inputscript.MultiTarget[inputscript.index] = collider.gameObject; inputscript.index++; The array class doesn't appeared in the inspector. To test if the array is filled, just print it using Debug.Log. Put one after MultiTarget.Add(collider.gameObject); line.