Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to do 2D HP bar outside Canvas like using the Image component?

Discussion in '2D' started by Nickromancer, Sep 13, 2020.

  1. Nickromancer

    Nickromancer

    Joined:
    Jul 31, 2016
    Posts:
    92
    From Image component, I could select Image Type to be Filled and use the Fill Amount to control how much a bar is filled.

    But how do I do the same thing if I want the HP Bar to be following my character in the scene but not inside a Canvas? Seems like I cannot use Image in this case. I have no idea how to do it with Sprite Renderer.
     
  2. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,503
    Take two SpriteRenderers. Give them a simple white square sprite. Put them on top of one another, the top parented to the bottom. The bottom is your "background" - set its color to, for example, red. The top one can be set to green. Stretch them using the transform's scale to the appropriate dimensions. At full HP, only the green one is visible by virtue of being on top. You can play around with resizing the green SpriteRenderer so that more of the red is exposed.

    As you should be able to see in the Inspector, this is just maniuplating the x-component of the transform's scale. Now all you need to do is reproduce this in code. If something is a little funny, try adjusting the pivot point of the white square to be on the left then setting the SpriteRenderer to use the pivot, but IIRC this shouldn't be necessary.

    ca.gif
     
    DeanTheodorakis likes this.
  3. Nickromancer

    Nickromancer

    Joined:
    Jul 31, 2016
    Posts:
    92