无法弄清楚如何让 Unity UI 正确缩放

Cant Figure Out how to get Unity UI to scale correctly

我正在尝试在 Unity 中的 UI 上显示健康栏,但无法弄清楚如何让缩放正常工作。我需要最左边的值为 0,所以当 currenthealth=0 时,条消失,当 currenthealth = maxhealth 时,它应该等于 maxhealth。我现在的代码如下。

    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;

}

您应该可以为此目的使用 UI 滑块。

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.

来源:https://docs.unity3d.com/ScriptReference/UI.Slider.html


此外,这里有一个关于 UI 滑块的视频教程,可能会有用:

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