- Home /
How can I use unity 4.6 gui to have a health bar that follows my enemy in world space?
From what I know of unity 4.6 gui so far, the only option I can think of is to create a world space canvas for each enemy just for the health bar. This will make for many many canvas in my scene. Is this the correct way to do this, or is there a better way? Again, I want to have each enemy have their own health bar hovering over their head in world space.
Answer by Stardog · Jan 10, 2015 at 08:59 AM
This is the cleanest way I can find of making a UI element follow a world object's 3D position.
public RectTransform canvasRectT;
public RectTransform healthBar;
public Transform objectToFollow;
void Update()
{
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, objectToFollow.position);
healthBar.anchoredPosition = screenPoint - canvasRectT.sizeDelta / 2f;
}
For many enemies, you will have to Instantiate the healthBar many times and store the instances in a list, then for loop through the list, setting their anchoredPosition.
Shouldn't World Space canvas be a working way to do this too, or have I completely misunderstood what that means. This particular solution (for me) requires additional smoothing to make it look better, it's a bit jittery as is.
I noticed he wanted World Space, but I haven't seen a game that does that for health bars. Starcraft 2, Dark Souls, $$anonymous$$ass Effect, etc, all use Overlay. I guess it's jittery because it's using screen pixels, so I suppose you could smooth it and uncheck Pixel Perfect.
This code doesn't work. The health bar is appearing WAY off screen.
It does work. Just be sure to check your Health Bar RectTransform Anchor and Pivot and adjust the Camera distance.
It doesn't work for every case, but after you make it work once you can adjust to your situation
Answer by GluedBrain · Sep 29, 2014 at 05:59 AM
That sounds quite normal, however, you should make sure that you save different kind of enemies as prefabs and use them as and when needed. In case you need an article on hoe to create a health bar check out the link below
TheGameContriver - Unity Health Bar
P.S. This would have been better posted in the forum rather though, as it was more of a discussion rather than a question.
This does not answer the question at all. The health bar doesn't show over the enemy.
Answer by Kiwasi · Sep 29, 2014 at 06:13 AM
Your onto the correct way to do it. Best bet is to include the canvas as a child object on whatever prefab you are using.
There are a couple options for the actual health bar too. You can use a slider. Or you can use any image and play with the fill effects.