Consider this Unity C# code snippet that gets the cell position of a world point in a Tilemap:
Vector3 worldPos = new Vector3(2.5f, 3.7f, 0f); Vector3Int cellPos = tilemap.WorldToCell(worldPos); Debug.Log(cellPos);
What will be printed in the console?
Vector3 worldPos = new Vector3(2.5f, 3.7f, 0f); Vector3Int cellPos = tilemap.WorldToCell(worldPos); Debug.Log(cellPos);
Remember that WorldToCell rounds down to the nearest cell coordinates.
The WorldToCell method converts a world position to the cell position by flooring the x and y values. So 2.5 becomes 2 and 3.7 becomes 3.
Given a Tilemap and a TileBase tile, what will this code print?
Vector3Int pos = new Vector3Int(1, 1, 0); tilemap.SetTile(pos, tile); TileBase result = tilemap.GetTile(pos); Debug.Log(result == tile);
Vector3Int pos = new Vector3Int(1, 1, 0); tilemap.SetTile(pos, tile); TileBase result = tilemap.GetTile(pos); Debug.Log(result == tile);
SetTile assigns the tile at the position, GetTile returns the tile at that position.
After setting the tile at position (1,1,0), GetTile returns the same tile object, so the comparison is true.
Look at this code snippet:
Tilemap tilemap;
void Start() {
Vector3Int pos = new Vector3Int(0, 0, 0);
TileBase tile = tilemap.GetTile(pos);
Debug.Log(tile.name);
}Why does this code throw a NullReferenceException?
Tilemap tilemap;
void Start() {
Vector3Int pos = new Vector3Int(0, 0, 0);
TileBase tile = tilemap.GetTile(pos);
Debug.Log(tile.name);
}Check if the tile exists at the position before accessing its properties.
If no tile exists at the given position, GetTile returns null. Accessing tile.name then causes a NullReferenceException.
In Unity Tilemaps, what happens if you change the Tilemap's origin property?
Think about how coordinates relate to tile positions.
The origin shifts the coordinate system of the Tilemap, so all tile positions are offset by the origin value.
Consider this code that sets tiles in a Tilemap:
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
Vector3Int pos = new Vector3Int(x, y, 0);
if ((x + y) % 2 == 0) {
tilemap.SetTile(pos, tile);
}
}
}
int count = 0;
foreach (var pos in tilemap.cellBounds.allPositionsWithin) {
if (tilemap.GetTile(pos) != null) count++;
}
Debug.Log(count);What number will be printed?
for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { Vector3Int pos = new Vector3Int(x, y, 0); if ((x + y) % 2 == 0) { tilemap.SetTile(pos, tile); } } } int count = 0; foreach (var pos in tilemap.cellBounds.allPositionsWithin) { if (tilemap.GetTile(pos) != null) count++; } Debug.Log(count);
Count how many positions satisfy (x + y) % 2 == 0 in a 3x3 grid.
Positions where (x + y) is even are (0,0), (0,2), (1,1), (2,0), (2,2) — total 5 tiles set.