Unity 中它应该如何工作 - slider.maxValue?

问题描述 投票:0回答:2

我请求有关“slider.maxValue = unit.maxHealth;”的帮助。 HP 条显示在必要预制件中所需对象的上方,其中滑块的最大值应等于角色的 maxHealth,当前值应等于角色的 Health。但是,当创建滑块时,它具有预制件指定的值,并且不会根据以下行进行更改: slider.maxValue = unit.maxHealth; slider.value = 单位.health;

public class StatusBarController : MonoBehaviour
{
    public GameObject   statusBarPrefab;
    public Transform    statusBarParent;

    private Slider      slider;
    private Image       fillImage;

    private void Start()
    {
        GameObject statusBarObject = Instantiate(statusBarPrefab, statusBarParent);
        slider = statusBarObject.GetComponentInChildren<Slider>();
        fillImage = statusBarObject.GetComponentInChildren<Image>();

        Unit unit = GetComponent<Unit>();
        slider.maxValue = unit.maxHealth;
        slider.value = unit.health;

        SetHPBarColorByTagPrefix();

        unit.OnHealthChanged += UpdateHPStatusBar;
    }

单位:

public class Unit : MonoBehaviour
{
    public int                        maxHealth;
    public int                        health;
    public int                        stamina;
    public int                        mana;
    public float                      m_speed;
    [HideInInspector] public bool     getDamaged;
    [HideInInspector] public bool     isAttackingBasicAttack;
    [HideInInspector] public bool     isAttackingHeavyAttack;
    [HideInInspector] public bool     isParrying;
    [HideInInspector] public bool     isDead;
    [HideInInspector] public bool     isStunned;
    [HideInInspector] public bool     isRooted;

    public event Action               OnHealthChanged;
}

我无法弄清楚问题的具体位置。

c# unity-game-engine game-engine
2个回答
0
投票

也许您应该尝试创建一种方法来在实例化时设置角色最大生命值。 在我的“健康栏”中:

公共类 HealthBar :MonoBehaviour { 公共无效SetMaxHealth(int health)
{ slider.maxValue = 健康; slider.value = 健康状况 } }


0
投票

修复了HP条,显然方法GetComponentInChildren()无法在HP条预制体的层次结构中正确检索滑块组件。我重新制作了预制件,将滑块组件放置在层次结构中最顶层的对象上,现在一切正常了。

© www.soinside.com 2019 - 2024. All rights reserved.