I was trying to create a debug view for my Water object in my Unity application. The problem is that I generate the water at runtime, which makes it impossible to see what it looks like in the editor mode. To resolve this, I created a script that draws a simple sprite representing my water:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
[ExecuteInEditMode]
public class WaterEditor : MonoBehaviour
{
[SerializeField] Sprite waterSprite;
GameObject debugWaterObject;
SpriteRenderer tileRenderer;
Water water;
void OnEnable() {
water = GetComponent<Water>();
}
void Update()
{
if (Application.isPlaying) {
Debug.Log("Destroying debug object");
Destroy(debugWaterObject);
return;
} else if (debugWaterObject == null) {
Debug.Log("Creating debug object");
debugWaterObject = new GameObject("Water Debug Object");
debugWaterObject.transform.SetParent(transform);
debugWaterObject.transform.localPosition = Vector3.zero;
tileRenderer = debugWaterObject.AddComponent<SpriteRenderer>();
tileRenderer.sprite = waterSprite;
tileRenderer.drawMode = SpriteDrawMode.Sliced;
}
tileRenderer.size = new Vector2(water.width, water.height);
}
}
The idea is that I create a debug object in editor mode and then destroy it in play mode. However, for some reason, when I run my application, I can still see the object in the editor:
I'm pretty sure that Destroy(debugWaterObject)
is called, and the object is not recreated in play mode. It seems that it is not being destroyed. I haven't been able to find any explanation for that. Why could this happen?