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.


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;