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 want the visual object to be removed from the scene. This recipe provides a simple way to link the ending of an audio clip that's playing with the automatic destruction of its parent GameObject
.
To wait for the audio to finish before destroying an object, follow these steps:
AudioObject
, and add an audio source component to this object.// file: AudioDestructBehaviour.cs using UnityEngine; using System.Collections; public class AudioDestructBehaviour : MonoBehaviour { private void Update() { if( !audio.isPlaying ) Destroy(gameObject); } }
// file: PlayDestroyButtonGUI.cs using UnityEngine; using System.Collections; public class PlayDestroyButtonGUI : MonoBehaviour{ public AudioDestructBehaviour myAudioDestructObect; private void OnGUI(){ bool playButtonWasClicked = GUILayout.Button("play"); bool destroyButtonWasClicked = GUILayout.Button("play then destroy"); if( playButtonWasClicked ){ myAudioDestructObect.audio.Play(); } if( destroyButtonWasClicked ){ myAudioDestructObect.audio.Play(); myAudioDestructObect.enabled = true; } } }
myAudioDestructObect
.AutoDestructBehaviour
(uncheck the box by this component).The game object named AudioObject contains an AudioSource component, which stores and manages the playing of audio clips. AudioObject also contains a scripted component, which is an instance of the AudioDestructBehaviour
class. When enabled, in 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 not to be playing the game object is destroyed. While the audio source is playing, then no action is taken.
The Main Camera scripted object PlayDestroyButtonGUI
offers two buttons to the user, both buttons send a Play()
message to the audio source component of the audio game object. However, when the Play then destroy button is clicked, the scripted component is also enabled. By enabling the scripted object, it means the logic in its Update()
method will be tested each frame, and as soon as the audio clip has finished playing, then the parent game object will be destroyed.
18.119.28.108