-4
\$\begingroup\$

This is driving me crazy. I am new to C# and I always get this error when playing while it seems like a very simple code.

I get the error at this line NullReferenceException: Object reference not set to an instance of an object.

HealthText.text = health.ToString();

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class damageHandler : Photon.MonoBehaviour {
    public int health = 10;
    public Text HealthText;
    public Text nameText;

    void Start(){
    //  HealthText.text = health.ToString();
    //  nameText.text = PhotonNetwork.playerName;
    }

    void OnTriggerEnter2D(){
        TakeDamage();
    }

    public void TakeDamage(){
        health --;
        HealthText.text = health.ToString();
    }

    void Die() {
        Destroy(gameObject);
    }

    void Update(){
        if (health <= 0){
            Die();
        }
    }
}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Hello, Abanoub. Take a look at this: stackoverflow.com/questions/4660142/…. Also, most of compiler problems are usually solvable by googling the error and find out how to improve your code. If your issues are source code-related only, better ask on the Programmers Stack Exchange \$\endgroup\$
    – liggiorgio
    Jun 8, 2016 at 9:51
  • \$\begingroup\$ I guess you don't input HealthText in inspector but you try this: HealthText = Getcomponent<Text>(); \$\endgroup\$ Jun 8, 2016 at 14:40

1 Answer 1

2
\$\begingroup\$

This looks like you have forgotten to assign the HealthText variable in the editor (drag and drop the text component to your script).

Also, make sure to read the post linked by liggiorgio in his comment.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .