Waiting for the audio to finish playing before auto-destructing an object
An event may occur (such as an object pickup or the killing of an enemy) that we wish to notify to the player of by playing an audio clip, and an associated visual object (such as an explosion particle system, or a temporary object in the location of the event). However, as soon as the clip has finished playing, we will want the visual object to be removed from the scene. This recipe provides a simple way to link the ending of a playing audio clip with the automatic destruction of its containing object.
Getting ready
Try this with any audio clip that is a second or more in duration. We have included the engineSound
audio clip inside the 04_06
folder.
How to do it...
To wait for audio to finish playing before destroying its parent GameObject, follow these steps:
- Create a new Unity 2D project and import the sound clip file.
- Create a GameObject in the scene containing an AudioSource component linked to the AudioClipengineSound...