- Home /
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
Answer by Joshua · May 07, 2011 at 04:15 AM
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.
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
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
It looks like this has to do with how I didn't reference the right object that contains the script component.. mea culpa!
Your answer
Follow this Question
Related Questions
How to check against the object type of an instance 1 Answer
Why this Texture gives value of Null when I access it from other script 1 Answer
Ray Casting - Trigger function 1 Answer
Fade 2 out of 3 gameobjects on the screen who have the same material 2 Answers
How to get a List of references of instances in a static variable 1 Answer