map.GetTile() returning null in onTriggerEnter2D
I have three Tilemaps in my project. One has the main map of the game. One is for items the player can pick up and one is for elements that influence the player.
If the player kills an enemy tiles get added to one of the two tilemaps. The tiles and Tilemaps are configured as triggers which works fine.
If the player collides with one of the tiles I want to check which kind of tile it was.
I use the following code:
private void OnTriggerEnter2D(Collider2D other)
{
Tilemap map = other.GetComponent<Tilemap>();
Vector3Int cellPosition = map.WorldToCell(transform.position);
string tiletype = map.GetTile(cellPosition).name;
switch(tiletype){
[...]
}
}
While this works in most of the cases, sometimes "map.GetTile(cellPosition)" returns null. So far I've tried:
- regenerating the Tilemap before the GetTile() call
- using LocalToCell instead of WorldToCell
- using LocalToCell only if WorldToCell returns null
All of them seemed to help a little but I'm still getting a lot of "null" responses. Has anyone had a similiar problem or has any idea what goes wrong?
Answer by Babsi1112 · Dec 09, 2017 at 02:36 PM
I've spent some more time on the problem and apparently for me using
Vector3Int position = new Vector3Int(
Mathf.RoundToInt(transform.position.x),
Mathf.RoundToInt(transform.position.y),
Mathf.RoundToInt(transform.position.z)
);
instead of
Vector3Int cellPosition = map.WorldToCell(transform.position);
seems to help.