Delay "Destroy(gameObject)"

I have a cube which I want to function in the following manner: when the player collides with the cube, a sound plays, and when the sound finishes (three seconds later), the cube s destroyed. Now how exactly do I do this?

If you want it to be precisely when the audio is finished, make sure the audio source isn't set to loop and use audio.IsPlaying() to determine if it's not playing anymore. Another way, if you know the exact length of the clip, is to use Destroy(gameObject, someTime); You might even be able to just use Destroy(gameObject, audioclip.length); but I remember reading somewhere that some compression settings makes the time not accurate.

2 Answers

2

I know this is a little bit older but:

Destroy has a second argument where you can make it wait for seconds

Example:

// Kills the game object in 5 seconds after loading the object
Destroy (gameObject, 5);

Here is the link for the Api: API Destroy

You do this using WaitForSeconds().

It’s easier in JavaScript (Unity script), but for C# you need to create special separate function for it.

//When you want to destroy it, call the function
StartCoroutine(Die());


//And function itself
IEnumerator Die(){
    //play your sound
    yield return new WaitForSeconds(3); //waits 3 seconds
    Destroy(gameObject); //this will work after 3 seconds.
}

Worked perfectly for me, thanks!