I have a problem with deleting tiles on hex. I'm sure that my hex position method is working for my project. I want to create tile which is breakable and changes sprite every specified damage done. Code was tested separately.
void NextTile()
{
if (currentTile == tiles.Length-1)
{
AddValue();
DestroyTile();
}
else
{
float offset = transform.parent.position.y;
Vector3Int pos = GetHexPosition(transform.position, offset);
tilemap.SetTile(pos, tiles[currentTile+1]);
Debug.Log("tile has been set, is it tile here?: " + tilemap.HasTile(GetHexPosition(transform.position, transform.parent.position.y)));
currentTile++;
}
}
void DestroyTile()
{
Vector3Int hexPos = GetHexPosition(transform.position, transform.parent.position.y);
tilemap.SetTile(hexPos, null);
Debug.Log("destroy tile ends, is it tile here?: " + tilemap.HasTile(hexPos));
}
It doesn't matter if i create this tile in script or not. HasTile() returns false after setting it to null, but the tile still exists in game (on paused game i can even delete it manually). GameObject is deleted.
I found a solution for colliders (code below), but i really want to use OnClick2D.
public void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player")
{
AddScore();
StartCoroutine("DelayedDestroy");
}
}
void DestroyTile()
{
Tilemap tilemap = GetComponentInParent<Tilemap>();
Vector3Int pos = Vector3Int.FloorToInt(transform.position);
tilemap.SetTile(pos, null);
}
IEnumerator DelayedDestroy()
{
yield return new WaitForEndOfFrame();
Destroy(this.gameObject);
DestroyTile();
EDIT: I found that this problem is with SetTile() method.
private void OnMouseDown()
{
Debug.Log("Clicked");
tilemap.SetTile(hexPos, null);
}
This code does not work as well on new project and new tilemap. hexPos is working because I can set other tiles in that place, but for some reason "null" not removing sprite from the tilemap.
EDIT 2: I found solution. For tilemaps in unity there could be more than once tile on same place. When you use brush to make maps it's set Z cord to 0 (or Z pos of tilemap?).