I've followed this tutorial (https://unity3d.com/pt/learn/tutorials/projects/roll-ball-tutorial/displaying-score-and-text) to make a Text updates every time my scripted score changes and it worked fine.
But i'd like to use TextMeshPro instead of the simple Text. I've already made all the necessary changes in my code, such as:
- using TMPro
- public TextMeshProUGUI scoreText; (instead of public Text scoreText)
- scoreText = gameObject.GetComponent(); (inside void Start())
- scoreText.text = "Score: " + score.ToString(); (inside my function)
When in Play Mode I receive the "NullReferenceException: Object reference not set to an instance of an object" message. I discovered the reason. When I enter Play Mode, I see in the Inspector that the TextMeshProUGUI that was assigned to the script is automatically unassigned.
I've made a stand alone script and added to a TextMeshProUGUI to check if my code was working with TextMeshPro, and it was. The thing is: I don't want one separated script only to update the TextMeshPro. I need, as the tutorial above, the TextMeshPro being a public variable inside a big script with all other functions.
If, after I enter Play Mode, I assign the TextMeshProUGUI manually by dragging it to the Inspector, the Score works! Why Texts, preFabs and everything stay assigned to my gameObject when I enter Play Mode, but the TextMeshProUGUI doesn't?
I think the code is ok, because it works if I assign the TextMeshProUGUI manually. But, anyways...
public class SnakeController : MonoBehaviour
{
public TextMeshProUGUI scoreText;
private int score;
void Start()
{
....
scoreText = gameObject.GetComponent<TextMeshProUGUI>();
score = 0;
setScoreText();
}
public void setScoreText()
{
scoreText.text = "Score: " + score.ToString();
}
}
The big issue is the TextMeshProUGUI be unassigned in the moment I enter Play Mode.