How can I create a health bar thats attached to a gameobject?

I’m relatively new to unity2d.I want to make a health bar that’s attached to a gameobject . It needs to move along with the players position and reduce or increase its horizontal width according to a variable.
I think using GUI.Box and creating a rectangle might work.But should I use it in this manner?
Or I could just reduce the x scale of another gameobject with a sprite.But doing so will make the width be reduces proportionally from both ends,if I’m right.How can I get it to stay fixed on the left end?

At first i recomment use the canvas system, it’s very easy to setup and you can place the pivot by hand to handle the direction. I made several videos about that.

Using Local Scale:


Using filled imageType:

Hope that helps. Cheers

To get place UI on top of a game object, you need to convert its world position to screenspace using the camera that is rendering the object. You can scale the width of the UI representation easily if you convert the health into a normalized 0 … 1 range.

I made an example that uses Unitys legacy GUI.Box since you asked for it, but consider adapting your solution to instead set the width of a UI item such as OctoMan pointed out.