Ray null reference

Hi all, can anybody spot why the following simple ray code is returning a null reference (NullReferenceException
UnityEngine.Camera.ScreenPointToRay (Vector3 position))?

public class MenuGUI : MonoBehaviour {
	
	
	RaycastHit myhit = new RaycastHit();
    Ray myray = new Ray();

	
	// Update is called once per frame
	void Update () {
	
		if (Input.GetMouseButtonDown(0)){
   		 myray = Camera.main.ScreenPointToRay(Input.mousePosition);

	        if (Physics.Raycast(myray, out myhit, 1000.0f)){
			print(myhit.collider.name);
			}
		}
	}
}

I’m trying to detect which object has been hit when the mouse clicks, they do have colliders attached

Found the answer, camera must be tagged as maincamera! sorry

1 Like