Hey I am getting Null Reference errors in two parts of my code as highlighted in below.
The first is the livesText.text in the UpdateDisplay() method. I’ve created Lives Text and assigned it the LivesDisplay script, the weird thing is whenever my UpdateDisplay() method is called it DOES update the text correctly to 5,4,3,etc yet the console says livesText.text is returning an “Object reference not set to an instance of an object” error. I don’t understand how that could be if its accessing .text just fine (I’ve tried replacing the line with GetComponent().text = “hello” and I still get the error).

In addition when lives go to zero it doesn’t load the game over scene (I’ve tried replacing it with LoadNextScene() and it still doesn’t work) I get the “Object reference not set to an instance of an object” error.
Does anyone have any ideas?

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

public class LivesDisplay : MonoBehaviour
    [SerializeField] int lives = 5;
    [SerializeField] int damage = 1;
    Text livesText;

    // Start is called before the first frame update
    void Start()
        livesText = GetComponent<Text>();

    private void UpdateDisplay()
        livesText.text = lives.ToString(); //here

    public void TakeLife()
        lives -= damage;

        if(lives <= 0)
            FindObjectOfType<Level>().LoadYouLose(); //and here

Hi Frank,

Welcome to our forum! :slight_smile:

NullReferenceException means that a reference (“link”) to an instance is missing. If you exposed a field in the Inspector, make sure that it’s not empty.

Since you wrote that the text gets updated correctly, check if you have multiple LiveDisplay scripts in your Hierarchy.

Zomg thanks! I had accidentally dragged the LivesDisplay script into my LivesText AND my EventSystem objects. Now that I’ve removed the one in the EventSystem that has resolved my first error.
Second error was just that I didn’t have the Level prefab object in my Level 1 Scene.

All fixed!


Good job! :slight_smile:

See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms