- Home /
Scale UI with distance
Hi! I am using Camera.main.WorldToScreenPoint for a health bar prefab I am using that displays on a canvas. How can I scale the size of the UI element of my health bar based on how far it is away to the Camera? I have a temporary system but it is completely trash. I want the health bars to look like they are floating above the enemies. Any help would be appreciated! Thanks.
I actually did switch to this once I found out I could do that. lol made my life easier
Answer by KittenSnipes · Feb 04, 2018 at 03:18 PM
@TheInventor
This will put the health on top of their heads. Put that script on your health texture or whatever it is and then drag the transform you wish it to follow.
public Transform target;
void Update (){
var wantedPos = Camera.main.WorldToViewportPoint (target.position);
transform.position = wantedPos;
}
I would also recommend you NOT put it on a canvas, which has the potential to do various transformation to its children objects, depending on the options you select for it.
Thanks but I already have that working. I want to modify the transform.localScale based on how far the target position is away from the camera. $$anonymous$$oving closer would make the healthbar bigger, but moving away would make the healthbar shrink, as if floating in 3d space above the target object.
This should happen automatically, just like it does to the character's themselves, if you DON'T put it on a canvas.
OOOOH! I only skimmed over the code and thought Camera.main.WorldToViewportPoint was Camera.main.WorldToScreenPoint. Sorry about that!
Your answer
![](https://koobas.hobune.stream/wayback/20220612151856im_/https://answers.unity.com/themes/thub/images/avi.jpg)