- Home /
need help to executing sound
Hello Unity community!
I ran into a problem that i can't figure out on my own. I added a few audio and sound clips to my project, i made all the other audio play when they are supposed to but i cant figure out the death sound. I realise that the audio can't finish before i call my "reload scene" method, but how do i make it delay so the audio can finish? here's the code.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Monster")
{
SoundManagerScript.PlaySound("deathsound");
Die();
}
private void Die()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
it instantly reloads the scene so the audio can't even start. how do i fix this?
thanks!
Answer by davidcox70 · Sep 12, 2020 at 06:30 PM
You could delay executing the Die() function by the duration of the audio clip.
So you could make a function in your SoundManagerScript that gets the duration of an audio clip using the audioClip.length property. Then use Invoke("die",clipDuration) to delay the execution of the Die() function.
https://docs.unity3d.com/ScriptReference/AudioClip-length.html
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
DC
Answer by rh_galaxy · Sep 12, 2020 at 06:31 PM
Something like this:
bool bRunGameOverTimer = false;
float fGameOverTimer = 0.0f;
private void Die()
{
bRunGameOverTimer = true;
SoundManagerScript.PlaySound("deathsound");
}
void Update()
{
//game end conditions
if (!bRunGameOverTimer)
{
//do other stuff while game is running
}
if (bRunGameOverTimer)
{
fGameOverTimer += Time.deltaTime;
if (fGameOverTimer > 5.0f) //delay for 5 sec before ending game
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Answer by zaditen · Sep 12, 2020 at 06:58 PM
Thank you guys so much! it works now! :D I tried the
if (collision.gameObject.tag == "Monster") { SoundManagerScript.PlaySound("deathsound"); Invoke("Die", 1.0f); } private void Die() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); }
Cheers!
Your answer
Follow this Question
Related Questions
Audio not coming out of speakers 1 Answer
FSBTool error while trying to import AudioSource. How to fix? 1 Answer
Play sound from an array, not random, and only once 3 Answers
Calling sound once in update 1 Answer
Play AudioSource Backwards 2 Answers