Why does PlayOneShot take an AudioClip but PlayDelayed does not?
I am confused by some differences between some of the audio functions available. I have several different sound AudioClips defined via inspector so I can easily play whichever sound I need to in my GameController class. Examples:
public AudioClip gunshot;
public AudioClip grunt;
public AudioClip yourMom;
soundSource.PlayOneShot(gunshot);
soundSource.PlayOneShot(grunt);
soundSource.PlayOneShot(yourMom);
But what confuses me that delayed playback does not take an AudioClip parameter. I would expect it to. It would make sense to me if it worked this way:
soundSource.PlayDelayed(grunt, 0.2);
How it really works:
soundSource.PlayDelayed(0.2);
But instead it only takes a delay parameter. So My question is, WHAT sound will it play delayed? Only the one single AudioClip set as the default via the Inspector? Then how do you manage many different audioclips that you want to play with various delays? Surely I am not expected to add multiple AudioSource components, right?
Answer by eatsleepindie · Mar 31, 2017 at 02:52 AM
You have a few options here:
Have a separate gameobject for each clip with it's own AudioSource then use PlayDelayed
Set the AudioClip component's clip variable to the desired clip before calling PlayDelayed
Use a Coroutine to create your own version of PlayDelayed (likely your best option). Example below
:
IEnumerator CoPlayDelayedClip( ) {
yield return new WaitForSeconds(1f);
soundSource.PlayOneShot(grunt);
}
Then simply call StartCoroutine(CoPlayDelayedClip()); instead. You can also pass clip and delay variables to the Coroutine like this:
IEnumerator CoPlayDelayedClip( AudioClip _clip, float _delay) {
yield return new WaitForSeconds(_delay);
soundSource.PlayOneShot(_clip);
}
Getting that code to format correctly after the list was a pain, sorry for all the revisions
Answer by quizcanners · May 28, 2020 at 01:01 PM
In addition to what eatsleepindie said, i'd recommend the second option. PlayDelayed is actually a really good thing since it gives time for Unity to prepare the sound in advance and play it independently of framerate. So it may give better performance overall.