x


Referencing instance of game object hit via RaycastHit

How do you reference an instance of a GameObject "hit" via RaycastHit?

I would assume it's this instanceHit = hit.transform.gameObject - where instanceHit is a global GameObject variable - but I get this error: NullReferenceException: Object reference not set to an instance of an object

more ▼

asked May 07 '11 at 04:08 AM

ina gravatar image

ina
3.3k 492 547 596

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

1 answer: sort voted first

Is your raycast actually hitting a collider/rigidbody? Else the nullreference would be obvious ;) if you're unsure how to test this just use if(physics.Raycast(etc)) which returns true if it hits something and false if it does not.

If you're sure that's not it, alternatively try using hit.collider.gameObject, which I have used successfully in the past. This wouldn't explain why hit.transform.gameObject does not work, though.

more ▼

answered May 07 '11 at 04:15 AM

Joshua gravatar image

Joshua
6.4k 19 25 70

hit.gameObject.name returns the right object name...

May 07 '11 at 04:20 AM ina

Are you perhaps constantly rdeclaring the variable hit and re-casting your ray without checking if it intersects or not? Because that would explain it sometimes working and sometimes throwing a NullReferenceException

May 07 '11 at 04:24 AM Joshua

i am constantly redefining hit, but each time, it's assigned to a global... the hit occurs only after the if(Physics.RaycastHit) ... so hit has to have hit an object each time

May 07 '11 at 04:29 AM ina

It looks like this has to do with how I didn't reference the right object that contains the script component.. mea culpa!

May 07 '11 at 06:51 AM ina
(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:

x2071
x261
x202
x161

asked: May 07 '11 at 04:08 AM

Seen: 1685 times

Last Updated: May 07 '11 at 04:08 AM