Making sounds wait for each other to finish

I’m trying to set up a script in which a sound begins to play at a certain point in time, which, in this case, is when the screen stops fading from black. I have a separate script that does that, and a public boolean that sets itself to true once the alpha of the image is less than .05. In my other script, the one I’m executing the sound from, I set up my sound manager as a public variable, and use it to play sounds in code. I have two sounds I would like to play in a sequence. However, I can’t figure out how to get the second sound to play only after the first one has finished, and with my current code, both sounds alternate with each frame.

Here’s my code so far: using UnityEngine;using System.Collections;public class BumpyScene : MonoB - Pastebin.com

Now, I’d prefer to just be able to define audio clips as variables and play them that way, but I can’t figure out how to get that to work.

Any suggestions?

You can do this by making use of a coroutine. That’s a function that you can delay before it starts. So you would do something like the following.

float lengthOfOriginalSound = sound.clip.length;
StartCoroutine(delayedPlay(lengthOfOriginalSound));


IEnumerator delayedPlay (float timeToWait)
{
   yield return new WaitForSeconds(timeToWait);

   // play second sound
}

In order to delay a function call, the function must have a return type of IEnumerator. When a function has this you can call the yield line above, which will pause execution of that function for the length of time you pass to it. Then after the yield has finished, you can play your new sound.

In order to call a function, you must call it with StartCoroutine() from your original function.

Also, this code is specific for C#. The syntax is a bit different if you are using Javascript.

If you always want to play those sounds in sequence, wouldn’t it be easiest just to combine them in one clip?