NullReferenceException when accessing another script.

I’m accessing another script to get its transform position but I get a repeating error NullReferenceException pointing to line 19 of my script.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

	Transform cam;

	CastleController castle;
	Vector3 castleCore;

	void Start ()
	{
		cam = transform;
	}

	void Update ()
	{
		castle = gameObject.GetComponent <CastleController> ();
		castleCore = castle.transform.position;

		CamMove ();
	}

	void CamMove ()
	{
		if (Input.GetKey (KeyCode.P))
			cam.Translate (Vector2.up * Time.deltaTime);
		if (Input.GetKey (KeyCode.Semicolon))
			cam.Translate (-Vector2.up * Time.deltaTime);
		if (Input.GetKey (KeyCode.L))
			cam.Translate (-Vector2.right * Time.deltaTime);
		if (Input.GetKey (KeyCode.Quote))
			cam.Translate (Vector2.right * Time.deltaTime);

		if (Input.GetKeyUp (KeyCode.P) || Input.GetKeyUp (KeyCode.Semicolon) || Input.GetKeyUp (KeyCode.L) || Input.GetKeyUp (KeyCode.Quote))
			cam.position = castleCore;
	}

}

Edit: Problem lied in the scripts being on different objects. Fixed by moving CameraController over to same object the other script was on and changing the transforms to Camera.main.

The most likely reason for this is CastleController is not attached to the same GameObject as CameraController.

If it is in another object, you may simply make the field “castle” public and drag and drop the object that contains the CastleController script to that field in the editor.

Thanks very much for the answer Joao! The thing you said about the scripts not being on the same object was the problem. I had the CameraController on the Main Camera and CastleController on the player sprite. Once I moved the CameraController script over to the player sprite object and changed some of the transforms to Camera.main everything worked! Thanks again!