【问题标题】:Weird Instatiate health bar奇怪的 Instatiate 健康栏
【发布时间】:2019-01-20 19:24:42
【问题描述】:

我正在尝试在我的单位上实例化生命条,问题是生命条在第一波单位的画布上反复实例化,而其他 2 波得到空画布。 该脚本位于单元预制件上。 我在单独的脚本中实例化单位和健康栏。 我不明白我在这里做错了什么。

这是一个截图:

private Transform player;
private Image healthBar;
private Image barFilled;
public GameObject hpBarPrefab;

void Start()
{     
    minionExp = GetComponent<MinionExperience>();
    initialHealth = MaxHealth;
    healthBar = Instantiate(hpBarPrefab, 
    GameObject.FindObjectOfType<Canvas>().transform).GetComponent<Image>();
    barFilled = new List<Image>(healthBar.GetComponentsInChildren<Image>()).Find(img => img != healthBar);
}

public void TakePlayer(Transform pl0)
{
    player = pl0;
}

public Transform GetPlayer()
{
    return player;
}

public void MinionsTakeDmg(int dmg)
{
    MaxHealth -= dmg;
    if (MaxHealth <= 0)
    {
        Destroy(gameObject);
        MaxHealth = 0;
        if (player != null)
            player.GetComponent<Levels>().GainExp(minionExp.MaxMinionExp);
    }
    UpdateHealthBar();
}

public void UpdateHealthBar()
{
    float fa = MaxHealth / initialHealth;
    if (healthBar != null)
        healthBar.fillAmount = fa;
}

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    GameObject.FindObjectOfType&lt;Canvas&gt;() 搜索整个场景,请改用FindComponentInChildrentransform.Find

    【讨论】:

    • 好的 :) 谢谢。
    【解决方案2】:

    已修复。只需使用公共图像并将我的健康条图像拖到上面,现在效果很好:)

    using UnityEngine.UI;
    using UnityEngine;
    
    public class RedMinionsHealth : MonoBehaviour
    {
        public float RedMaxHealth = 10;
        private float RedinitialHealth;
        private MinionExperience minionExp;
        private Transform player;
        public Image RedhealthBar;
    
        void Start()
        {
            minionExp = GetComponent<MinionExperience>();
            RedinitialHealth = RedMaxHealth;
        }
    
        public void TakePlayer(Transform pl0)
        {
            player = pl0;
        }
    
        public void MinionsTakeDmg(int dmg)
        {
            RedinitialHealth -= dmg;
            if (RedinitialHealth <= 0)
            {
                Destroy(gameObject);
                RedMaxHealth = 0;
                GetComponent<BulletTieToPlayer>();
                if (player != null)
                    player.GetComponent<Levels>().GainExp(minionExp.MaxMinionExp);
            }
            UpdateHealthBar();
        }
    
        public void UpdateHealthBar()
        {
            float fac = RedinitialHealth / RedMaxHealth;
            if (RedhealthBar != null)
                RedhealthBar.fillAmount = fac;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      相关资源
      最近更新 更多