Adding an object to an array only if it is not in the array

I am trying to add and object to an array. I am trying to check if the object is already in the array, if it isnt, then add it. If the object is in the array then I dont want to add it. The issue that I am running into, is that my script continuously adds the object to the array. Here is what I have so far :

for ( var i : int = 0; i < activearray.Length; i++ )
				{
				var selectedobject : GameObject = activearray*;		*
  •  		if ( selectedobject == hit.collider.gameObject)* 
    
  •  		{*
    
  • 			Debug.Log("tile is already grouped");*
    
  •  	}* 
    
  •  	else* 
    
  •  	{* 
    
  •  	 activearray += [hit.collider.gameObject];*
    
  •  	}*
    
  •  }*
    

Unityscript Javascript arrays are slow, as far as I have read.

It’s better to just simply use a list for this functionality, because it already has a method to check if an object exists in the list.

if( yourList.Contains( hit.collider.gameObject ) )
    Debug.Log("Tile is already grouped");
else
    yourList.Add( hit.collider.gameObject );

remember to add System.Collections.Generic to your import / using statements.

Imagine that you have an array of 10 entries, and the object in question is one entry in the array. Your code will loop through the array and add hit.collider.gameObject for every entry that’s not the same game object, so it will be added 9 times.

You should use List instead of an array if you’re adding items to a collection. In that case you can just use List.Contains to see if the object is in the List or not.