'OnTriggerEnter' - add object to array

I recently posted a question with 2 problems in it…one problem was solved (thank you ‘sparkzbarca’), so now i have to deal with the other.

I have a bad guy with a sphere collider (set to isTrigger) which is quite large and detects when a civilian NPC passes into it. At this point, i’m trying to add that civilian to an array when it enters the sphere-trigger.

With my current code, when i print the length of the array, it only shows ‘1’, now matter how many civilians enter. What am i doing wrong?

    var target : GameObject;
     
    var newCiv;
     
    function OnTriggerEnter (targets : Collider) {
    if (targets.tag == "civilian"){
    print ("civilian In Range");
     
    newCiv = targets.gameObject;
    print(newCiv);
    }
    }
     
     
    function Update () {
    civPos = newCiv.gameObject.transform.position;
    var civTargets = new Array();
     
    civTargets.Add(civPos);
    print(civTargets.length);
     
    }

I’m sure the answer is staring me in the face, but i just can’t see it. All help is always appreciated.

Tom :slight_smile:

You’re setting civTargets as a new Array every Update, which replaces the previous array with a brand new empty one every frame. Try moving the array construction outside of the Update function and into the script’s scope, such as target is.

Also, if you are adding civPos to the array every Update, the array will just grow in size forever. You probably want only one position added per NPC, so you should just add it in the OnTriggerEnter call. Try this instead:

var target : GameObject;

var civTargets = new Array();

function OnTriggerEnter (targets : Collider)
{
    if (targets.tag == "civilian")
    {
        print ("civilian In Range");

        var civPos = targets.gameObject.transform.position;
        civTargets.Add(civPos);
    }
}


function Update ()
{
    print(civTargets.length);
}

You might also want to remove from the array OnTriggerExit as well.