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>();
UpdateDisplay();
}
private void UpdateDisplay()
{
livesText.text = lives.ToString(); //here
}
public void TakeLife()
{
lives -= damage;
UpdateDisplay();
if(lives <= 0)
{
FindObjectOfType<Level>().LoadYouLose(); //and here
}
}
}