I am programmatically placing 4 large dots on my 2D scene which already has some objects on it. If the new dot overlaps an existing object I want to destroy the existing object. All the objects have 2Dcolliders and all are on the same layer ("Action").
Since I only do this once during the initial setup of the game I don't want to use collision detection events, instead it would seem that Collider2D.OverlapCollider would be the way to do this but I can't get it to work. The following code is called from Start() after all the objects have been placed, and thinking it might be something to do with the colliders not being active until the first frames, I also called it from a mouse click with the same result (no overlaps).
void EraseOverlapDots()
{
GameObject[] largeDots = GameObject.FindGameObjectsWithTag("LargeDot");
foreach(GameObject ldot in largeDots)
{
Debug.Log("Object:" + ldot.tag + "(" + ldot.transform.position + ")");
Collider2D collider = ldot.gameObject.GetComponent<Collider2D>();
ContactFilter2D contactFilter2D = new ContactFilter2D();
contactFilter2D.SetLayerMask(ldot.layer);
contactFilter2D.useLayerMask = true;
List<Collider2D> collisions = new List<Collider2D>();
int colCount = collider.OverlapCollider(contactFilter2D, collisions);
int i = 0;
foreach (Collider2D col2d in collisions)
{
i++;
Debug.Log("HIT"+i+":" + col2d.tag + "(" + col2d.transform.position + ")");
}
}
}
In an attempt to debug this I purposely put 4 small dots in exactly the same position as the large dots to ensure they overlap. When I run the game they are visibly exactly on top of each other but the result is always zero overlaps.