- Home /
The question is answered, right answer was accepted
Enemy Health Bar UI
Hi. I making a 2D rpg game. I need enemy health bar to instantiate over the enemy and follow it. I create a prefab of canvas with the bar. Canvas is set to World Space. But when bar instantiates, it starts to strangely flying everywhere. It follows enemy, but not in the right way. Here is a line of code that follows the enemy:
void Update () { gameObject.transform.GetChild (0).transform.position = enemy.transform.position + new Vector3 (0, enemy.transform.position.y + 1f, 0); }
Yes, its kinda messy, but pls help me someone. Thanks.
Why not just make the UI element a child of the enemy and set the offset yourself? As far as making it appear to "instantiate", just grab the component in script and turn it on/off as needed.
Answer by Glurth · May 26, 2016 at 08:47 PM
gameObject.transform.GetChild (0).transform.position = enemy.transform.position + new Vector3 (0, 1f, 0);
removed "enemy.transform.position.y + " from the offset. Otherwise, you are doubling the y position. of the child(0) object.
But Hanoble's commet is right, just make it a child (looks you actually have already), set the offset (local position) once, and be done with it.