Exemplo n.º 1
0
    void AddTilemapCollider2Ds(Transform parent)
    {
        // find all grids
        Grid[] grids = GameObject.FindObjectsOfType <Grid>();
        foreach (Grid grid in grids)
        {
            // find tilemaps (we only care about those that have colliders)
            var tilemaps = grid.GetComponentsInChildren <Tilemap>().Where(
                tm => tm.GetComponent <TilemapCollider2D>()
                ).ToList();

            foreach (Tilemap tilemap in tilemaps)
            {
                // go through each cell
                BoundsInt bounds = tilemap.cellBounds;
                for (int y = bounds.position.y; y < bounds.size.y; ++y)
                {
                    for (int x = bounds.position.x; x < bounds.size.x; ++x)
                    {
                        // find out if it has a collider
                        Vector3Int cellPosition = new Vector3Int(x, y, 0);
                        if (tilemap.GetColliderType(cellPosition) != Tile.ColliderType.None)
                        {
                            // convert to world space
                            Vector3 worldPosition = tilemap.GetCellCenterWorld(cellPosition);

                            // note: creating a primitive is necessary in order for it to bake properly
                            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                            go.isStatic         = true;
                            go.transform.parent = parent;
                            // position via offset and transformpoint
                            go.transform.position = new Vector3(worldPosition.x, 0, worldPosition.y);
                            // scale depending on scale * collider size (circle=radius/box=size/...)
                            go.transform.localScale = NavMeshUtils2D.ScaleTo3D(tilemap.transform.localScale);
                            // rotation
                            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(tilemap.transform.eulerAngles));

                            MakeUnwalkable(go);
                        }
                    }
                }
            }
        }
    }