raycasting in c# - NullRefrenceException error

First off, I appreciate you time,

I’m trying to make an object move on a plane according to the location of the cursor (mouse) by “clicking and dragging”

When I try and code a raycast script onto that object I get a NullRefrenceException error upon clicking on that object.

here is a part of my code:

void Update () {
	if (Input.GetMouseButton(0)) 
        {
            RaycastHit hit = new RaycastHit();
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//**** 
        if (Physics.Raycast(ray, out hit)) {
            Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
            hit.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
        }
    }

**** is where the error occurs.

What am i missing? any ideas?

Thanks!!

This could happen if there’s no camera in your scene tagged “MainCamera”. See the documentation here. If you don’t have a camera with that tag, then Camera.main returns null, and then calling ScreenPointToRay is a NullReference.

Fantastic! it worked like a charm.
I have used raycasting before in java script but now C# I thought I was missing something.
Turns out, as you said, since i created a new camera in place of the other main camera it was no longer tagged as the main. Therefor I was receiving null references.

Thanks a million!