- Home /
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!!
Answer by CHPedersen · Aug 02, 2011 at 07:30 AM
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.
Answer by Roventae · Aug 02, 2011 at 09:58 AM
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!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Object reference not set to an instance of an object 1 Answer
AI raycasting problem 0 Answers
Distribute terrain in zones 3 Answers
NullReferenceException when an object is in the way that is not the player 1 Answer