x


NullReferenceException: Object reference not set to an instance of an object, Raycasting

I made a unity game about a month ago right after C# training and I seemed to have learned a lot and was able to finish it, but I haven't coded in about a month and it really sucks I forgot a lot of stuff. Simple stuff is annoying me right now. I'm trying to Raycast from my middle of my view and then get the name of the object I'm looking at in my console but I'm getting a error at the debug.log line. Here is my code. Also can anyone recommend some stuff to read to get refreshed on how to read unity C# code again?

void Update () {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit = new RaycastHit();
    Debug.Log(hit.collider.gameObject.name);

}

more ▼

asked Jul 31 '12 at 10:26 AM

cj31387 gravatar image

cj31387
86 14 25 34

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

1 answer: sort newest

You forgot to actually call the raycasting. See Physics.Raycast.

Your code should look like:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
    Debug.Log(hit.collider.gameObject.name);

Note: the last parameter distance is optionnal. Default is Mathf.Infinity but it is always a good idea to set it to a sound value to improve performance and to prevent catching a very far object that is almost invisible to the player.

more ▼

answered Jul 31 '12 at 11:24 AM

Kryptos gravatar image

Kryptos
7.2k 5 32

(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:

x1528
x161
x8

asked: Jul 31 '12 at 10:26 AM

Seen: 912 times

Last Updated: Aug 01 '12 at 07:47 AM