How to add to list if not in list

I’ve been creating a sighting system which will add players to an array of seen targets if they come within the trigger and then i’ll be doing some raycasting to check weather they’re in front of me. The problem i’m having is adding the object to the list if it isn’t in the list. The way it hopefully will work is this line will be called when an enemy has wandered into the trigger(by the enemy)

function OnTriggerEnter(other : Collider)
{
	target.gameObject.SendMessage("AddToArray", gameObject,SendMessageOptions.DontRequireReceiver);
}

and this is called by the ally when the enemy sends the message

import System.Collections.Generic;

var enemies : List.<GameObject>;

function AddToArray (newTarget : GameObject)
{ 
		enemies.Add(newTarget);
}

As I said there was no error, just I want it to add the enemy to the list, if it isn’t in the list

thanks in advanced

You can use List.Contains():

if (!enemies.Contains(newTarget)) {
    enemies.Add(newTarget);
}

Bear in mind that can be an expensive call if your list is huge (hundreds or thousands of items).

You can use the collection’s IndexOf method. It will return -1 if the object isn’t found.

if (enemies.IndexOf(newTarget) < 0)
{
    enemies.Add(newTarget);
}

If uniqueness of items is important and order doesn’t matter consider using a HashSet. This will ensure items in your collection are not duplicated, and is much faster if you need to insert into a large collection frequently (it’s O(1) to determine uniqueness instead of O(n)).

I’m not sure how to do it in UnityScript but in C#:

HashSet<GameObject> hs = new HashSet<GameObject>();