- Home /
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?
You could use Physics.Raycast() and use layers or tags to decide if the object that was hit should play a sound.
Answer by fafase · Aug 01, 2012 at 07:27 AM
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);
I get some errors:
Assets/Scripts/heartbeat.js(7,64): BCE0005: $$anonymous$$ identifier: 'hit'.
Assets/Scripts/heartbeat.js(8,12): BCE0005: $$anonymous$$ identifier: 'hit'.
i use this but nothing happends:
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=="Enemy"){ audio.Play(); } } }