An event may occur (such as an object pickup or the killing of an enemy) that we wish to notify to the player 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 wish for 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.
Try this with any audio clip that is a second or more in duration. We have included the engineSound
audio clip inside the 1362_09_04
folder.
To wait for audio to finish playing before destroying a GameObject, follow these steps:
engineSound
audio clip and drag it from the Project view to populate the Audio Clip parameter of the Audio Source component of AudioObject, and deselect the component's Play On Awake checkbox:using UnityEngine; using System.Collections; public class AudioDestructBehaviour : MonoBehaviour { private AudioSource audioSource; void Start(){ audioSource = GetComponent<AudioSource>(); } private void Update(){ if( !audioSource.isPlaying ) Destroy(gameObject); } }
AudioDestructBehaviour
scripted component of AudioObject (when needed, it will be re-enabled via C# code):using UnityEngine; using System.Collections; public class ButtonActions : MonoBehaviour{ public AudioSource audioSource; public AudioDestructBehaviour audioDestructScriptedObject; public void PlaySound(){ if( !audioSource.isPlaying ) audioSource.Play(); } public void DestroyAfterSoundStops(){ audioDestructScriptedObject.enabled = true; } }
Play Sound
text, and attach the ButtonActions script to this button.Destroy When Sound Finished
, and attach the ButtonActions script to this button.The GameObject named AudioObject contains an Audio Source component, which stores and manages the playing of the audio clip. AudioObject also contains a scripted component, which is an instance of the AudioDestructBehaviour class. This script is initially disabled. When enabled, every frame this object (via its Update()
method) tests whether the audio source is not playing (!audio.isPlaying
). As soon as the audio is found to be not playing, the GameObject is destroyed.
There are two UI buttons created. Button PlaySoundButton calls the PlaySound()
method. This method will start playing the audio clip, if it is not already playing.
The second button called DestoryWhenSoundFinishedButton calls the DestoryAfterSoundStops()
method. This method enables the scripted component AudioDestructBehaviour in GameObject AudioObject—so that that GameObject will be destroyed, once the sound has finished playing.
18.220.184.6