- Home /
How to destory gameObject without destroying the audio source attached to it?
How can I destroy a GameObject without destroying the sound effect attached to it? I tried a coroutine to wait 3 seconds before the object is destroyed so the sound can finish playing but it didn't work.
public class DestroyByBoundary : MonoBehaviour {
IEnumerator WaitToDestroy(Collider2D other) {
yield return new WaitForSeconds(3);
Destroy (other.gameObject);
}
IEnumerator OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "platforms") {
yield return WaitToDestroy(other);
//Destroy (other.gameObject);
}
}
}
Answer by MrSoad · Nov 10, 2014 at 11:13 PM
The only way I can think of is to have the audio source on a child object. Then un-parent it just before you destroy it. You can then set this now separate audio source object to destroy itself once the audio has finished playing.
Or you can disable all aspects of the object, colliders, rigidbodys, and renderers, then wait until the audio has finished playing and destroy it then.
while (audio.isPlaying) {
yield;
}
//Then Destroy.
Answer by Cherno · Nov 11, 2014 at 01:02 AM
As a workaround, why not disable all relevant components, but leave the AudioSource? So you would disable all scripts and the MeshRenderer, and keep only the AS active.
Your answer
Follow this Question
Related Questions
Sound plays right at the beginning 2 Answers
Multiple Cars not working 1 Answer
Problems with Audio Sources 1 Answer
How to mute specific audio sources? 3 Answers
Distribute terrain in zones 3 Answers