My issue is that i am trying to add everything that collides with a certain trigger to an array, and htis part works to my knowledge (although there may be problems with the values it adds) the biggest probelm is making sure it doesn;t add the same thing twice.
My script is as follows:
var colliders = new Array();
function OnTriggerEnter (other : Collider)
{
if (!colliders.contains(other.gameObject))
{
colliders.Add(other.gameObject);
}
}
function Update()
{
print(colliders);
}
However with the addition of the “if(!colliders.contains(other.gameObject))” line it doesn’t add them to the array anymore.
Any ideas why this is?
Thanks, Tom.
If that’s the exact code and you don’t have #pragma strict at the top of the file then it’s probably because you’ve used contains with a lowercase “c” rather than “Contains”.
However you’d be much better off using a HashSet (which is O(1) for detecting an existing entry and ensuring only one of each type can be in there compared to the O(n) operation of Contains).
import System.Collections.Generic;
var collders = new HashSet.<Collider>();
You should never really use Array - always use a generic collection (e.g. List) as they are much better. There’s info here.
You are using javascript, so I don’t have code for you, but I use HashSet.
In C# you include the using System.Collections.Generic;
Hashset is like a list but provides uniqueness. I use it for exactly what your are using it for.
Remember to remove it when OnTriggerExit() is called.