[Solved] Cannot get raycasting to work

Hello everyone,

even though I worked with raycasts before, I am unable to figure out why I get this error message:

“NullReferenceException: Object reference not set to an instance of an object”

My scene has one cube in it and I want to get the name of the cube by casting a raycast after pressing a mouse button. The code is as following:

 void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("MouseBotton 0 is down");
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {               
                Debug.Log(hit.collider.gameObject.name);
            }
        }
    }

But it does not work and I cannot get my head around it why it does not.
Can anyone explain the problem to me?

Thanks in advance.

I recreated the scene and now it works. I think the problem was, that the camera I used was not the original Main Camera and therefore the ray could not be created since the camera reference was wrong…