Issue with writing variables to other scripts.

I’m working on pickups for my game, and every time I try to write the variable from one script to another it keeps giving me this error:

NullReferenceException: Object reference not set to an instance of an object. CoinScript.OnTriggerEnter2D(UnityEngine.Collisder2D Trigger)(at Assets/Scripts/CoinScript.cs:11)

Obviously the code would be useful, so here is the script for the pickup:

using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {

	public DataKeeperScript dks;

	void OnTriggerEnter2D (Collider2D Trigger) {
		if(Trigger.gameObject.tag == "Player"){
			Debug.Log ("Coin collected");
			dks.score += 1;
			Destroy(gameObject);

		}
	}

}

And here is the script for the player that keeps the score.

using UnityEngine;
using System.Collections;

public class DataKeeperScript : MonoBehaviour {

	public int score = 0;
	

}

As you can see, the code is small, and has no frills so far, any help would be appreciated!

-Soviet Bear

In your code:

public DataKeeperScript dks;

You are telling Unity to expose the dks variable in the editor. Make sure that you drag your Player object (or whatever object has the DataKeeperScript) into the dks slot! See below:

Left: No object specified (NULL reference).

Right: Object specified. you’re good to go!

45878-dks2.png

Alternatively, if there is only one instance of DataKeeperScript in your scene, you could do this instead:

 public class CoinScript : MonoBehaviour {
 
     private DataKeeperScript dks;

     void Awake () {
          
          // finds the first instance of DataKeeperScript in your scene
          dks = FindObjectOfType<DataKeeperScript>();
     }
 
     void OnTriggerEnter2D (Collider2D Trigger) {
         if(Trigger.gameObject.tag == "Player"){
             Debug.Log ("Coin collected");
             dks.score += 1;
             Destroy(gameObject);
 
         }
     }
 
 }