x


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!!

more ▼

asked Aug 01 '11 at 10:22 PM

Roventae gravatar image

Roventae
1 1 1 1

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Aug 02 '11 at 07:30 AM

CHPedersen gravatar image

CHPedersen
6k 13 22 61

(comments are locked)
10|3000 characters needed characters left

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!

more ▼

answered Aug 02 '11 at 09:58 AM

Roventae gravatar image

Roventae
1 1 1 1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4178
x1536
x399
x58

asked: Aug 01 '11 at 10:22 PM

Seen: 1465 times

Last Updated: Aug 02 '11 at 09:58 AM