Get List of Tilemap Collider parts per Script

Hello! :slight_smile:

I put a Tilemap Collider on my Tilemap (in this case the lava layer). In addition a Composite Collider. Now I would like to place a 2D light in the middle of each collider. (Simply via “m_Collider.bounds.center;” and some cell codes) However, I can’t find a way to get a list of all Tilemap collider sections.

Do you have any idea how I could realize that?

Have a great day!

Hi @JayNiize

“In addition a Composite Collider. Now I would like to place a 2D light in the middle of each collider.”

So you need the centers of composite collider created blobs? It sounds like that, as why would you like to place anything to each tile / collider, if you ask about composite colliders…

It is actually possible, although I haven’t used Tilemap let alone composite collider that much;

  1. Get the composite collider attached to your Tilemap in your script.
  2. Get the path count of this composite collider (how many blobs).
  3. Iterate paths (blobs).
  4. For each blob, get its point count and calculate center of points. Store these somewhere.

Now you should have a list of centers for each blob created by Tilemap Composite collider paths.

Then again, if you need the location every tile, these you can get easily with Tilemap itself at least.

1 Like

@eses Hey!

Thank you very much for this ingenious tip! I was really stuck. It’s all going the way it’s supposed to!
Here is my code for those who have a similar problem!

  [SerializeField]
    List<Vector2> centerList;
    void CheckCompositeCollider()
    {
        var compCol = tileMap.GetComponent<CompositeCollider2D>();
        for (int i = 0; i < compCol.pathCount; i++)
        {
            Vector2[] points = new Vector2[compCol.GetPathPointCount(i)];
            compCol.GetPath(i, points);
            float xCenter = 0;
            float yCenter = 0;
            for (int x = 0; x < points.GetLength(0); x++)
            {
                xCenter += points[x].x;
                yCenter += points[x].y;
            }
            centerList.Add(new Vector2(xCenter / points.GetLength(0), yCenter / points.GetLength(0)));
        }

        for(int i = 0; i < centerList.Count; i++)
        {
            Instantiate(light2d, centerList[i], Quaternion.identity);
        }
    }
2 Likes