0

Sorry for the newb question.

I am trying to make a panel display the players final score after the game ends, I copied some code from a brackeys video but it still doesn't work.

I've tried initializing the text variable as null, I've tried some different syntax as well.

Here is the script that displays the score while the player is playing the game. This part works just fine.

using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
    private float timer;
    public Text scoreText;

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        scoreText.text = timer.ToString("0.#");
    }
}

This script is meant to pull the score from the first script and display it on a text object on the game over panel.

using UnityEngine;
using UnityEngine.UI;

public class DisplayScore : MonoBehaviour
{
    public Text finalScore;

    void OnEnable()
    {
        finalScore.text = GetComponent<Score>().scoreText.text.ToString();
    }
}

The game is working quite well except for this null reference error. error come from this line in the second script:

finalScore.text = GetComponent<Score>().scoreText.text.ToString();
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
games247
  • 65
  • 1
  • 10
  • 1
    Is `finalScore` referenced in the Inspector? Is `scoreText` referenced in the Inspector? – derHugo Jul 24 '19 at 15:41
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – derHugo Jul 24 '19 at 15:42

1 Answers1

1

Since in Unity the Text constructor is protected, you must access an existing Text object you have created in the editor. Something like this

finalScore = someGameObject.GetComponent<Text>();
finalScore.text = timer.ToString("0.#");

or create a Text object with .AddComponent<Text> as shown here: Text.text

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188