非 Monobehaviour 属性创建 NullReferenceException

Non Monobehaviour attribute create NullReferenceException

我是 Unity/C# 的新手,我找不到问题的答案 :0

我有一个脚本 (selectCharacter),可以将脚本 (Knight) 添加到游戏对象。 Knight 脚本调用方法 "SetResource(true)"。此方法创建 NullReferenceException。问题是由属性 "private Attribute health" 产生的(属性是非单行为 class)但我不知道为什么,因为我去了骑士脚本 manuel 到 gameobject 一切都很好。

感谢您的帮助,抱歉我的英语不好。

    public class SelectCharacter : MonoBehaviour {
       void Start () {
          gameObject.AddComponent(typeof(Knight));
       }
    }

    public class Knight : PlayerStandardAttribute
    {
       void Start () {
       SetResource(true)
       }
    }

    public class PlayerStandardAttribute : MonoBehaviour {

       private Attribute health;

       public void SetResource(bool healthP) {
          if (healthP == true){
          Debug.Log(health.ToString());
          health.CurrentBar = GameObject.Find("HealthBar").GetComponent<Bar>();        
          }
    }

在调用 SetResource 之前,您需要创建一个 Attribute 实例并将其分配给 health。它将类似于:

void Start () {
   health = new Attribute();
   SetResource(true);
   }