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!