0

I am new in Unity/C# and i cant find a answer for my problem :0

I have a script(selectCharacter) which adds a script (Knight) to a gameobject. The Knight-script calls the method "SetResource(true)". This method creates a NullReferenceException. The problem is generate by the attribute "private Attribute health" (Attribute is a non-Monobehaviour class)but i dont know why, because went i but the knight-script manuel to the gameobject everything is fine.

Thanks for help and sorry for my bad english.

    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>();        
          }
    }
Omgoor
  • 3
  • 1

1 Answers1

0

You'll need to create an instance of Attribute and assign it to health before calling SetResource. It will be something along the lines of:

void Start () {
   health = new Attribute();
   SetResource(true);
   }
0liveradam8
  • 752
  • 4
  • 18
  • Hey, thanks dude, i solve the problem, but i have to create the intance in PlayerStandardAttribute. Something like this: public class PlayerStandardAttribute : MonoBehaviour { private Attribute health; void Awake(){health = new Attribute();} – Omgoor Aug 17 '17 at 11:59