How to make a sound play when my flashlight (spotlight) hits an object

I would like to make a sound play when a spotlight (acting as a flashlight) hits an object. I tried making it with a hover function, but for some reason it didn’t work. Is there any other way?

Add a raycast to your light.Put this script on your light object.

var sound:AudioClip;

function Start(){
   audio.clip = sound;
}
function Update () {
    var hit:RaycastHit
    if (Physics.Raycast (transform.position, transform.forward,hit, 10)) {
        if(hit.collider.gameObject.tag=="ObjectTagged"){
            audio.Play()
        }
    }
}

This will throw an invisible ray in front of your light for 10m. If the ray hits an object it checks the tag of the object and if it matches then it plays the sound loaded.

If you want to see the actual ray in the Scene view (you cannot see it in the game view), you can use:

Debug.DrawLine (transform.position, transform.forward, Color.red);