Search Unity

Audio Having Audio Play BEFORE Player Dies

Discussion in 'Audio & Video' started by VFranklin, Oct 1, 2019.

  1. VFranklin

    VFranklin

    Joined:
    Jul 26, 2017
    Posts:
    48
    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.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class Player_Main : MonoBehaviour
    7. {
    8.        
    9.     public GameObject enemy_1; // Enemy is named Enemy
    10.  
    11.     public AudioClip enemy_clip;
    12.     public AudioSource enemy_source;
    13.    
    14.     void Start()
    15.     {
    16.         enemy_source.clip = enemy_clip;
    17.     }
    18.     void OnCollisionEnter(Collision col)
    19.     {
    20.  
    21.        if
    22.        ((col.gameObject.name == "Enemy"))
    23.         {
    24.             enemy_source.Play();
    25.             Destroy(player);
    26.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    27.         }
    28.    
    29.    
    30.  
    31.     }
    32. }
    Any help would be greatly appreciated. Thank you.
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    140
    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: https://johnleonardfrench.com/articles/how-to-play-audio-in-unity-with-examples/#clip_at_point

    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.

    Code (CSharp):
    1. public class PlayAudio : MonoBehaviour
    2. {
    3.     public AudioClip clip;
    4.     public float volume=1;
    5.  
    6.     void Start()
    7.     {
    8.         AudioSource.PlayClipAtPoint(clip, transform.position, volume);
    9.     }
    10. }
    Edit: Forgot to add an example.