Destroying UI elements problem

Hello there,

I am trying to build floating health bar which follows enemies and to do that I created a prefab based on UI Slider object. In my script that controls enemy health I have public GameObject healthBar; variable which is associated with this prefab. Good to mention that after creating this healthBar it is set to be child of my HUD canvas.

And now comes the problem!

When I kill enemy I call:

Destroy(healthBar);

I also tried:

Destroy(healthBar.gameObject);

but it simply wont destroy it.

I solved it by adding Remove function to script which controls health bar and does exactly the same (calling Destroy(gameObject)); and it worked.

My question is why the first approach isn’t doing the thing?

Thanx

Your code seems logically, my only theory is that you have healthBar linked to the wrong object. For example, you have it linked to the prefab not the in game object.

Try gaining access to it at run time, by either finding it via GameObject.Find(“”); or simply by making HealthBar GameObject public or [SerializableField] in your inspector and dragging and dropping the exact object you want destroyed.

Another advice I can offer, is try destroying something else, or if it is a UI 4.6 problem. Perhaps make HealthBar a child of an empty object, then destroying that object.

Hope this helps.