Having Audio Play BEFORE Player Dies

Hi,

I have a game scene where when the player collides with an enemy, the player is destroyed and the scene restarts. But how can i have a collision sound effect play before the scene restarts?
I had assigned the AudioSource to the Player but I’m thinking it might not make sense if the payer is destroyed upon collision and if I want to have a collision sound effect.

Here’s some code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Player_Main : MonoBehaviour
{
       
    public GameObject enemy_1; // Enemy is named Enemy

    public AudioClip enemy_clip;
    public AudioSource enemy_source;
   
    void Start()
    {
        enemy_source.clip = enemy_clip;
    }
    void OnCollisionEnter(Collision col)
    {

       if
       ((col.gameObject.name == "Enemy"))
        {
            enemy_source.Play();
            Destroy(player);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    
   
  
    }
}

Any help would be greatly appreciated. Thank you.

If you want to play a sound from an object when it’s destroyed, that isn’t immediately cut off, one option is to use Play Clip at Point. This creates a temporary Audio Source at a position you specify (the player transform for example) and is cleaned up after the sound finishes playing.

I wrote an article about it: Blog - John Leonard French

Then you may wish to delay the restarting of the scene with Invoke or with Wait for Seconds in a Coroutine to give the sound time to play.

public class PlayAudio : MonoBehaviour
{
    public AudioClip clip;
    public float volume=1;

    void Start()
    {
        AudioSource.PlayClipAtPoint(clip, transform.position, volume);
    }
}

Edit: Forgot to add an example.