Error NullReferenceException: Object reference not set to an instance of an object

Hi

It was working, then this error just came out of nowhere. Don’t understand whats going on.

Its a top down shooter and the idea being that it aims and shoots using the curser.

Can anyone offer any suggestions please. Really am stuck with this one. :slight_smile:

public class PlayerController : MonoBehaviour 
{
	//handling
	public float rotationSpeed = 1000;
	public float speed = 20;
	public float fireRate;

	private float nextFire;



	//system
	private Quaternion targetRotation; //stores direction
	public PlayerBoundary boundary;


	//components
	private CharacterController controller;
	private Camera cam;

	public GameObject shot;
	public Transform shotSpawn;


	
	
	void Start()
	{
		controller = GetComponent<CharacterController> ();
		cam = Camera.main;
		
	}
	

	void Update()
	{

	ControlMouse ();
          
		if (Input.GetButton ("Shoot") && Time.time > nextFire) 
		{
			nextFire = Time.time + fireRate;
			Instantiate(shot, shotSpawn.position, shotSpawn.rotation);

			audio.Play ();


		}
	}


	



	void ControlMouse()
	{



		//set up direction in input variabe
		Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"),0, Input.GetAxisRaw("Vertical")); 

		//Sets up mouse position
		Vector3 mousePos = Input.mousePosition;
		mousePos = cam.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
		shotSpawn.LookAt(mousePos);



		if (input != Vector3.zero) //fingers taken off controls, player doesnt reset to defaul position
		{
			targetRotation = Quaternion.LookRotation(input); //rotates player in the way of the direction
			transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, rotationSpeed * Time.deltaTime);
		}

		//Controls Movement 
		Vector3 motion = input;
		motion *= (Mathf.Abs (input.x) == 1 && Mathf.Abs (input.z) == 1) ? .7f : 1; //moving diagonally doesnt travel at twice the speed

		controller.Move (motion * speed * Time.deltaTime);



	}





}

this is a duplicate question. did you search for your error message? i’ve answered this the same way several times now, and that’s just me.

null reference exception: “something before a . is null”.

Line 66 (of 65-66, assuming your line numbers in this code are correct), only has one thing before a . that can be null, and that is ‘cam’. Since you set cam = Camera.main in start, either line 66 is called before start (during awake), or you have no camera that is tagged “MainCamera”.