- Home /
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
All of the above should work from anywhere so far that your "healthBar" or "helthBar" references the correct health bar.
Try adding a unique health bar to your enemy with a unique tag or any other unique value and in the place where you call Destroy call Debug.Log(healthBar.someUniqueValue);
Sorry about my spelling err :D I tried Debug.Log(healthBar.GetComponent().maxValue);
and it logged 1 which is default value of prefab and not the value I set latter. This led me to the source of problem which is:
What I was doing is dragging and dropping healthBar prefab to my public GameObject healthBar;
. And when I call Instantiate I didn't save the return value to my healthBar variable. This means that I was calling destroy on prefab and not the instance of that prefab? Am I right? I'm new to this Unity stuf :) I'm a bit confused now cause I do something like this:
healthBar = (Instantiate (healthBar, transform.position, Quaternion.identity) as GameObject);
I use same variable to instantiate object and to save that object back. This works but I'm not sure what happens under the hood?
And thanx for help :)
Answer by KitoCode · Apr 09, 2015 at 04:53 PM
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.
For example, you have it linked to the prefab not the in game object.
Yes, it was exactly this! Thanx!