using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
Text score;
public static int coinAmmount = 1;
void Start() {
score = GetComponent<Text> ();
}
void Update()
{
score.text = "Score: " + coinAmmount.ToString();
}
}
And it works fine, the counter is incremented on screen when i get a coin. But it still gives me this error:
NullReferenceException: Object reference not set to an instance of an object
Score.Update () (at Assets/Scripts/Score.cs:17)
public Text score; // drag yout Text UI inside the inspector
Now you don’t need to get the component Text on Start anymore and your code should work now.
Edit:
To explain why you’re getting that error message, You’re grabbing the UI Text not the Text.text so when you try to use Text.text it is sending you a null reference because it is empty. I’m not 100% sure but using your method you could probably still accomplish .enabled = true/false;
But I think it’s just better to drag it in the field and not worry about grabbing an object on load.
with public Text score; you can see the field in the inspector. If the game is paused because of error, switch in the scene (by paused game) tab and check if this field is empty (can it be that you have deleted the ui-text somewhere in the game)?