- Home /
What to do to hear a voice over only 1 time?
Hi! I have a question. In my game, you hear a voice over. Right now, the voice overs (different audio sources) are connected to the player. Example, the player walks to an empty bottle and grabs it (VR), then you will hear a voice over "Hmm, empty, I need to refill this". This bottle is connected to a script with 2 public audio sources and a void OnTriggerEnter, as follows
public class TriggerSFX : MonoBehaviour
{
public AudioSource playSound;
public AudioSource playSound2;
void OnTriggerEnter(Collider other)
{
playSound.Play();
playSound2.Play();
}
}
The audio source with the line "Hmm, empty, I need to refill this" is connected to the player. This audio source will be put in the public audio source playSound. This works, but not as I want it to do. I only want the sound to be heard just 1 time. Right now, you will hear this sound everytime you pick the bottle up. And further, you see 2 audio sources and 2 triggers. This is because in some cases, I want 2 voice overs on one trigger but the second voice over a bit later, couple seconds, with delay. I've searched the whole internet to find the answers for both questions and tried many things, but I just couldn't figure it out. Can someone help me with this?
Answer by Captain_Pineapple · Jul 06, 2020 at 01:14 PM
okay here we go.
this script should fix most of your problems. It can play dialogue delayed or one after the other. This version however will specifically play each audio once per object. So if there are 2 bottles both will play the audio once. Hope this is what you wanted, let me know if something is unclear here.
public class TriggerSFX : MonoBehaviour
{
public AudioSource playSound;
public AudioSource playSound2;
//boolean flag to keep track if the OnTriggerEnter function of *this specific* object has been triggered yet.
private bool hasPlayed = false;
void OnTriggerEnter(Collider other)
{
if (hasPlayed)
return;
hasPlayed = true;
playSound.Play();
//this will play the sound 2 after a time of 10 seconds. The Gameobject/Component must not be disabled in this time.
StartCoroutine(delayedSFX(playSound2, 10f));
//alternative approach to play sound if the first one has finished:
StartCoroutine(SFXEnqueue(playSound, playSound2));
}
private IEnumerator delayedSFX(AudioSource playSource, float timeDelay)
{
yield return new WaitForSeconds(timeDelay);
if(!playSource.isPlaying)
playSource.Play();
}
private IEnumerator SFXEnqueue(AudioSource waitForSource, AudioSource playSource)
{
yield return null;
while(waitForSource.isPlaying)
{
yield return null;
}
if (!playSource.isPlaying)
playSource.Play();
}
}
Answer by Timvb_97 · Jul 08, 2020 at 10:14 AM
Hi @Captain_Pineapple, thank you so so much! It works now! Exactly how I want it to, yesss!
Your answer
Follow this Question
Related Questions
recording sound from external input 0 Answers
[NoBraves] Sound makes lag 1 Answer
GetSpectrumData doesn't update 2 Answers
need help to executing sound 3 Answers