Score Text not updating - object reference not set...I thought it was

I have a ScoreManager attached to my canvas. As children of this canvas I have two UI.texts, Player 1 Score Text, and Player Score 2 Text.

In my ScoreManager script I have 2 public text variables, player1score and player2score. In the editor I have dragged both UI.texts into the corresponding public variables.

In my Score Manager I have a small bit of code to update the text with the players score, which it is not doing. I am getting an object reference not set error.

I don’t understand this as I have set the object by dragging the UI.Text into the variable in the editor, haven’t I?

I am debugging each players score to console and this is working correctly. Just the text output.

public class ScoreManager : MonoBehaviour {

    public Text player1Score;
    public Text player2Score;

    private int player;

    public  int p1score;
    public  int p2score;


    void Start () {
        p1score = 0;
        p2score = 0;  
    }
     

    // Update is called once per frame
    void Update () {
     
    }

    public void setPlayerHit(int player, int scoreValue)
    {
     

        if (player == 1) {
         
            p1score += scoreValue;
            player1Score.text = "Player 1: " + p1score;
            Debug.Log ("Player 1: " + p1score.ToString());

        }

        if (player == 2) {
            p2score += scoreValue;
            player2Score.text = "Player 2: " + p2score;
            Debug.Log ("Player 2: " + p2score.ToString());
        }
    }


}

The code works for me, have you tried restarting unity?

Just restarted - still the same error. Strange.

Can you show the error?
Also you might have accidentally attached the script on multiple game objects

I’ve fixed it making it private and attaching it in script instead with:
player1Score = GameObject.Find ("Player1ScoreText").GetComponent<Text>();

Strange how the other didnt work. Thanks for replying :slight_smile:

Still strange though as it worked for me :roll_eyes:

1 Like

Still wondering if you maybe had multiple of those scripts, could always try something like this

public void Start(){
Debug.Log(transform.name);
}

and see if it shows up multiple times.

And if u ever need help u can always add me on discord Doil#1582

1 Like