How it should work - when i click on the UI button, the score increases and is displayed using text.
How it's working - An error that says 'NullReferenceException: Object reference not set to an instance of an object'
There are two scripts on two different game objects.
Player Script
using UnityEngine;
public class Player : MonoBehaviour
{
ScoreManager scoreManager;
private void Start()
{
scoreManager = new ScoreManager();
}
public void UpdateScore()
{
scoreManager.IncrementScore();
}
}
ScoreManager Script
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
private int score = 0;
public TextMeshProUGUI scoreText;
public void IncrementScore()
{
score ;
scoreText.text = score.ToString();
}
}
When I use Debug.Log(score.ToString()), it displays the score in the console. But when I use textmeshprougui, it gives an error.
Also, I've dragged the text into the inspector, so that cannot be a problem for the null referrance. I've checked it multiple times.
Why am I not able to update the text from another script?
CodePudding user response:
Null reference exception is in your Player.cs script and caused because of the code in your Start()
method
ScoreManager scoreManager;
private void Start()
{
scoreManager = new ScoreManager();
}
Remove the code in your Start()
method. Because there is a field ScoreManager scoreManager;
, you drag the gameobject which has the script ScoreManager.cs into its slot in the Player.cs script. Now you have the reference of the ScoreManager.cs script in your Player.cs script.
Now, you are resetting its reference in your Start()
method. This caused the null reference exception.