Search code examples
c#unity-game-engineunity-ui

Cant Figure Out how to get Unity UI to scale correctly


I am trying to get a health bar to display on my UI in Unity and cannot figure out how to get the scaling to work correctly. I need the Left most value to be 0 so when currenthealth=0 the bar disappears and when currenthealth = maxhealth it should be equal to maxhealth. My current code is as follows.

    public RectTransform this_rect;
public float left = 3f;
public float right = 0f;
public float posY = -50f;
public float height = 20f;
public int MaxHealth = 3;
public int currentHealth = 3;
void Update()
{
    this_rect.anchorMin = new Vector2(0, 1);
    this_rect.anchorMax = new Vector2(1, 1);
    Vector2 temp = new Vector2(left, posY - (height / 2f));
    this_rect.offsetMin = temp;
    temp = new Vector3(-right, temp.y + height);
    this_rect.offsetMax = temp;
   // currentHealth = (int)(left + 1 * MaxHealth);
    right = -currentHealth + MaxHealth;

}

Solution

  • You should be able to use a UI slider for the purpose.

    The slider component is a Selectable that controls a fill, a handle, or both. The fill, when used, spans from the minimum value to the current value while the handle, when used, follow the current value.

    Source: https://docs.unity3d.com/ScriptReference/UI.Slider.html


    Additionally, here is a video tutorial on the UI slider which may be useful:

    UI Sliders can be used for various purposes from settings menus to health bars.

    https://unity3d.com/learn/tutorials/topics/user-interface-ui/ui-slider