Neighbors for Non-Grid

I’m working on trying to get neighbors matching a given type using oncollisionenter and exit to manage a list of them. I’m scratching my head as I’m trying to understand the best way to do this. It’s non grid based, so I however could use an array. I see as that I’m constantly adding and removing neighbors it should be a list.

Something like this.

private List<GameObject> Neighbors = new List<GameObject>();

private void OnCollisionEnter(Collision c)
{
		Neighbors.add(c.gameObject);
}

private void OnCollisionExit(Collision c)
{
		Neighbors.remove(c.gameObject);
}

I imagine this isn’t a very fast way to handle neighbors but given that it’s non grid I can’t imagine alternatives.

The actual problem tho, is that it’s not removing anything from the list on collision exit.

Besides the methods of a list starting with uppercase (Add, Remove) I see nothing wrong with this code. It should work.

However, this might be a better approach:

To get the surrounding objects of any object in your scene, you can use Physics.OverlapSphere or Physics.OverlapBox, which both return an array of colliders.