Physics.OverlapSphere + adding GameObject to list that has multiple colliders

Hi everybody,

So I have a function that is simply searching for colliders within a radius and then I want to add the gameobjects that those colliders are attached to to a list.

The problem I am having is that each gameobject has two colliders attached, so each time my function runs each gameobject gets added to the list twice.

Can anybody give me some help or direction in best practise to find each game object but only add it to the list once?

The objects are likely to have duplicate names and tags.

Many thanks!

Pretty easy. Don’t add the collider or colliding transform itself, but use Transform.root instead which will return itself if it already is the root.
Then you can also check with Generic Lists whether they already contain an object, so something like this will help:

Transform rootTransform = collidingTransform.root;
if (!collidingObjectsList.Contains(rootTransform)
    collidingObjectsList.Add(rootTransform);
2 Likes

Thank you very much @Glockenbeat , I haven’t had a chance to implement your code yet but I will be looking into it later today.

Just before you posted I also had some luck using a simple IF statement: !objectList.Contains(hit.gameObject) as well.

I am still learning and Im glad that you have shown me an alternative way of doing things :slight_smile: