0
\$\begingroup\$

So I made a game where you shoot a laser and if it hits the enemy it makes an explosion sound and destroys the enemy. The only thing is whenever I try to get the audio to play it doesn't which I assume is caused by the enemy being destroyed. I have tried to use the Play() methods and PlayOneShot() methods but they both don't seem to help me out.

This is my current code:

public AudioClip explosion;
public AudioSource explosionAudioSource;

public void OnTriggerEnter2D(Collider2D other)
    {
    
    void Start() {
    explosionAudioSource = GetComponent<AudioSource>();
    }
        if (this.tag == "Enemy" && other.tag == "Laser")
        {
            explosionAudioSource.PlayOneShot(explosion);
            Destroy(other.gameObject);
            Instantiate(enemyExplosion, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
            Destroy(this.gameObject);
            uiManager.UpdateScore();
        }

Thanks!

\$\endgroup\$
  • \$\begingroup\$ How exactly do you expect the audio source to play sound when you've destroyed it? This is like taking a sledgehammer to your speakers then wondering why the music stopped. Did you try playing the sound from an audio source that you're not destroying? \$\endgroup\$ – DMGregory May 1 at 17:21
  • \$\begingroup\$ I did try with 3 other audio files, they all work properly. Just when I assign the audio to play before the enemy dies is when it destroys. \$\endgroup\$ – ItsDJJuju May 1 at 18:47
0
\$\begingroup\$

I was able to fix my problem by instantiating a prefab with the audio source onto it and have it play on awake when the object was instantiated it would play the sound perfectly.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.