- Home /
Audio Toggle Background Music (With Trigger )
I have a trigger that changes my camera into a new scene. My current code for the background music is this:
var Sound : AudioClip;
function OnTriggerEnter(){ audio.PlayOneShot(Sound); }
It's very simple. I would like to use my trigger to turn off this music and start another. That doesn't seem too difficult, it's when I leave that trigger. I would like to keep the main Background music and have it turn on again when you exit the trigger, and turn off the trigger music. (so toggle them.)
This is what I have so far, but I'm not sure if I'm on the right track.
var Sound1 : AudioClip; var Sound2: AudioClip;
function OnTriggerEnter(){ audio.PlayOneShot(Sound1);
if (OnTriggerEnter("CabinV1 Trigger")) { audio.Pause(Sound1); audio.PlayOneShot(Sound2); }
If (OnTriggerExit("CabinV1 Trigger"))
{
audio.PlayOneShot(Sound1);
audio.Pause(Sound2);
}
}
I'm fairly new to this but I hope this was enough information. Please help!
Thank you!
Answer by JesusChristChangedMe · Dec 11, 2010 at 02:51 AM
I know exactly what you want. Checkout the question about audio. You might also want to see the script reference on OnTriggerExit
So you can do something like.
var Sound1 : AudioClip; var Sound2 : AudioClip; function Start() { audio.Play(Sound1); }
function OnTriggerEnter(other:Collider) { if(other.gameObject.tag == "CabinV1 Trigger") { audio.Pause(Sound1); audio.Play(Sound2); } }
function OnTriggerExit(other:Collider) { if(other.gameObject.tag == "CabinV1 Trigger") { audio.Pause(Sound2); audio.Play(Sound1); } }
Just make sure you have an audio listener attached to your player.
Answer by Spence89 · Jul 16, 2011 at 03:31 PM
May I ask where I would put this code please? I am looking for something very similar :)
Many thanks, Adam