0

Hey guys so I have am a new programmer. For the school's intake, i have to make a unity game. So I decided to make a scrolling shooter. I have two scripts one on a game object and the other on a UI element. I want to change the score in the UI element from the game object when it is destroyed. But I keep getting this error code whenever I kill the object: NullReferenceException: Object reference not set to an instance of an object EnemyController.Update () (at Assets/Scripts/EnemyController.cs:22)

The enemyController is a prefab and will be spawning multiple. This is the offending code:

public class EnemyController : MonoBehaviour {

public ScoreUi scoreUi;

void Update(){
        if (health <= 0) {
            Destroy (gameObject);
            scoreUi.score++;
        }
    }
}

And this is the UI script Line 22 is a UI.Text object that is throwing the NULL exception marked by !!!.

public class ScoreUi : MonoBehaviour {


    static int score = 0;
    public Text Score;

    // Update is called once per frame
    void Update () {
    //This is line 22.
!!!    Score.text = "Score: " + score.ToString ();
}

Any help would be appreciated!

  • Which line is line 22? – maccettura Feb 13 '17 at 16:54
  • You need to drag the GameObject `ScoreUi` script is attached to to the `scoreUi` variable slot in the `EnemyController` script. You can also use GetComponent to do that. – Programmer Feb 13 '17 at 16:57
  • If you decide to do it with script, add this to the `EnemyController` script: `void Start(){scoreUi = GameObject.Find("Name Of Object ScoreUi Is Attached To").GetComponent( );}` – Programmer Feb 13 '17 at 17:00

0 Answers0