"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!

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.

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))