- Home /
"NullReferenceException: Object reference not set to an instance of an object" When Raycast hits and tries select a designated object
This script is acting strange... I have tried solutions from other answers but they don't seem to work at all. I have a ray that constantly checks for GameObjects with the layer "Interactable". The ray has no difficulty identifying the objects, but when it tries to selected it and store it in a variable for further purposes, it returns this error: "NullReferenceException: Object reference not set to an instance of an object"
Here's the script:
#pragma strict
var cam : Transform;
var layerMask : LayerMask;
function Update () {
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if(Physics.Raycast(cam.transform.position, cam.forward, 100, layerMask))
{
var selectedObject : GameObject = hit.transform.gameObject;
Debug.Log("You hit something");
}
}
I've also tried this but it didn't work either:
var selectedObject : GameObject = hit.collider.gameObject;
What is wrong? Thanks!
Answer by Eno-Khaon · Apr 25, 2016 at 11:34 PM
You're not actually assigning anything to "hit".
When you fire a Raycast, you need to ensure that you use the variant of the function in which the outgoing variable is read and modified.
if(Physics.Raycast(cam.transform.position, cam.forward, 100, layerMask))
// Change to...
if(Physics.Raycast(cam.transform.position, cam.forward, hit, 100, layerMask))
You definitely need it for C#, but you don't actually need if for JS.
// C#
if (Physics.Raycast(ray, out hit))
// JS
if (Physics.Raycast(ray, hit))
Answer by fight_1977 · Apr 26, 2016 at 04:25 AM
u used a wrong overload of Physics.Raycast, no out parameter named hit in the function parameter lists. so hit is a undefined variable, then the NullReferenceException error.
Your answer
Follow this Question
Related Questions
Raycast script help? 1 Answer
Switch GameObjects Tags with javascript 1 Answer
detecting reycast collisions 1 Answer
Make tranform follow raycast 1 Answer
Raycast Distance Help 1 Answer