How To Play Audio Over A Yield

Hi guys, I’m new to Unity and have been searching the forums extensively to sort every issue before posting - this one I need some assistance though

Essentially I want to play a sound (some dialogue)… The gameplay stops while the sound plays… then after the sound has finished, continue the script. I’m using a yield in c# via StartCoroutine and whats happening is - even though I’ve set the audio to play before the yield, the yield activates… then afterwards the sound fires.

   public IEnumerator speech2(string audioName)
   {
     
       //misc code..

     //prepare audio!!
     AudioClip au_dialogue_clip;
     au_dialogue_clip = (AudioClip) Resources.Load (audioName);
     au_dialogue.clip = au_dialogue_clip;
     
       //disable player movement during the audio!
       PlayerMovement.game_PlayerHasControl = false;
     
     //play audio!
     au_dialogue.Play();

     //wait for audio to finish..
     yield return new WaitForSeconds (au_dialogue_clip.length);
     PlayerMovement.game_PlayerHasControl = true;     
     ;
   }

The au_dialogue is an audiosource declared at the start of the class, the class is faily big so only included the releveant parts :slight_smile:

I tried using another coroutine to play the sound to see if that would work too…
Where it says au_dialogue.Play() now - I tried StartCoroutine (playAudio ());

To call…

  private IEnumerator playAudio ()
   {
     yield return new WaitForSeconds(0);
     au_dialogue.Play ();

   }

This had the same result though, the audio came after the yields!

Would appreciate some help, thanks :slight_smile:

Maybe try yielding like this:

au_dialogue.Play();
while( au_dialogue.isPlaying )
{
     yield return null;
}

Also, if your clip is fairly large loading it from resources could hurt framerate. You might consider the WWW class and placing your audio file in the StreamingAssets folder, or simply set your clip to stream from disk and have it referenced in the scene, not loaded from resources.

Cheers,

Gregzo

That got it! Thanks a lot, Gregzo :slight_smile: