Search code examples
c#unity-game-engineaudio-source

Audio clip not playing after collision


I have been facing an audio issue for 3days. I was looking to play audio after the collision. Not getting any proper idea OR where the problem occurs in my scenario, I could not solve my problem. In my GameObject, I added Audio Source through 'Add Component' where I put my mp3 file into AudioClip and also checked off 'Play On Awake'.

NB : PlayExplosionAnimation() and Destroy() are working fine.

public class Player : MonoBehaviour
{

    private AudioSource source;

    void Start()
    {
        source = GetComponent<AudioSource>();
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Rocks")
        {
            source.Play();
            PlayExplosionAnimation();
            Destroy(gameObject);
        }
    }

}

Solution

  • The problem is that the AudioSource is attached to the game object which has been destroyed immediately after the collision is detected so you never actually hear the sound. One potential solution could be to delay destroying of the game object by specifying how many seconds you want to delay the destroying, e.g. delay for 0.5 second.

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Rocks")
        {
            source.Play();
            PlayExplosionAnimation();
            Destroy(gameObject, 0.5);
        }
    }