I spent quite a while on this problem and it’s starting to bug me out. It’s not crashing the game or anything, just a little annoying, but the basic gist of it is that I have a custom tile with associated game object:
public class GrassTile : TileBase
{
public GameObject tileGameObject;
public Sprite sprite;
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
tileData.gameObject = tileGameObject;
tileData.sprite = sprite;
}
}
So far so good, and here’s the script for the tile object itself:
public class GrassTileObject : MonoBehaviour
{
private GameObject _objectOnTile;
private Tilemap _tilemap;
private void Start()
{
_tilemap = FindObjectOfType<Tilemap>();
}
public GameObject ObjectOnTile => _objectOnTile;
public void SetObjectOnTile(GameObject objectOnTile)
{
_objectOnTile = objectOnTile;
}
private void OnDestroy()
{
_tilemap.SetTile(_tilemap.WorldToCell(transform.position), null);
}
}
OnDestroy() is triggered when the field _health is <= 0:
public class Health : MonoBehaviour
{
[SerializeField] private int _health;
public int HealthPoints => _health;
public void TakeDamage(int damage)
{
_health -= damage;
if (_health <= 0)
{
EventManager.Instance.TriggerEntityDiedEvent(GetComponent<Entity>());
Destroy(gameObject);
}
}
}
Now the problem is that for some reason whenever the associated tile object is destroyed, Unity is insisting that I’m destroying the object multiple times:
Destroying object multiple times. Don’t use DestroyImmediate on the same object in OnDisable or OnDestroy.
UnityEngine.Tilemaps.Tilemap:SetTile (UnityEngine.Vector3Int,UnityEngine.Tilemaps.TileBase)
GrassTileObject:OnDestroy () (at Assets/Scripts/GrassTileObject.cs:27)
If I comment out the “_tilemap.SetTile(_tilemap.WorldToCell(transform.position), null);” line, the error is gone. I’m thinking the reason could be that when the tile is set to null, the associated game object is destroyed, but I couldn’t find any information on that, so I’m just blind guessing.
Any ideas on how to fix this?