How to access a variable on another script

When I’m trying to access a variable and methos on another script, I’m getting an error:


public class MoveSphere : MonoBehaviour
	void Start()
        // NullReferenceException: Object reference not set
        // to an instance of an object MoveSphere.Start ()
	    GetComponent<TargetScript> ().myVar = 5;
	    GetComponent<TargetScript> ().ShowVar ();


public class TargetScript : MonoBehaviour
    public int myVar;

    public void ShowVar()
        Debug.Log (myVar);

The only error i can think about is you get MissingComponentException because your TargetScript is not on the same object as your MoveSphere.

Either fix this, or find the gameobject that has got a TargetScript component.
You can use GameObject.Find();


you can have a public GameObject member in your MoveSphere script and assign it in the inspector with the object that has TartScript component