Find Position of Specific Tile in Tilemap in OnTriggerEnter2D Method

Hey guys. Relatively new to Unity. I've found some threads that kind of talk about this but I haven't found an answer that works for me yet.

I have a trigger attached to my character that changes a variable if a specific type of tilemap block is in range.

My trigger code is very simple right now. It looks like this:

private void OnTriggerEnter2D(Collider2D trigger)
    {
        if (trigger.gameObject.CompareTag("Tag"))
        {
            variable = true;
        }
    }

What I want is to find the specific Vector2 coordinates of the block that the trigger is colliding with, then store them for other behaviour. I have tried poking around in the components of the tilemap and the Collider2D/gameObject methods listed on Unity, but I haven't found anything that has worked for me yet. The closest I have come is the closestPoint method, which does seem to behave consistently, but I'm worried it might choose the wrong block if there are multiple near each other.
Feels like there's an obvious answer that I'm missing. Let me know if there's a solution here.

A collider on a tilemap is only one collider (and important to note that a tilemap is one component on a game object, the tiles aren't 'separate'). It doesn't have knowledge of the individual tiles, or at least you don't get that information through collisions, and of course you only get the collider in the case of a trigger.

So as it stands an OnTriggerEnter2D will trigger once when it starts intersecting with a tilemap collider, and only trigger again if this trigger box as completely left contact with that tilemap's collider.

Perhaps the solution here is to flip around the logic. Use a rule tile that has a game object (and a sprite) reference, which has a trigger that checks for the player and does whatever it wants to do when said player enters its area.

2 Likes