NullReferenceException: Object reference not set to an instance of an object (134700)

i dont understand why im getting this problem, here’s my script
public class Pause : MonoBehaviour {

	public Text label;
	public DistanceSystem anotherScript;
		// Use this for initialization
	void Start () {

	}
	void Awake(){
		anotherScript = GetComponent<DistanceSystem> ();
	}
	// Update is called once per frame
	void Update () {

		label.text = anotherScript.distanceTravelled.ToString ("F0");
	}

i dragged the text that the distancesystem is attached to it as the public distancesystem anotherscript, and label is the text i want to display the score at
distance system looks like this

	public Transform player;
	public  Text label;
	public float distanceTravelled; 
	float lastPosition;



	void Start () {

		lastPosition = player.transform.position.y;

	}
	
	// Update is called once per frame
	void Update () {
		distanceTravelled = player.transform.position.y - lastPosition;
		label.text = distanceTravelled.ToString ("F0")+"m";

		} 		

which works fine, just when i press pause it doesn’t print it where i want it and returns the error in the title

Reading questions tagged with NullReferenceException is always a good plan. I'd have closed this as a duplicate if your question didn't already have an answer.

1 Answer

1

i will assume your null error exception points you at the code inside your Pause Update function. That error means you are trying to access an object which is not there, which means the anotherScript variable is null. Which leads us back to your awake function. This implies that the initilization statement in the Awake function does not work(it is not capturing anything). You can post the code when you press the pause button to see what you are trying to do

im using the OnClick() of the new UI

Try the code in Start rather than Awake. The object might not be available at that moment.

And be sure the object is enabled when the scene starts