[c#]Does audio.Play() work only in Update and Start funcitons?

Im Instantiating enemies and trying to make explosion sound when enemy is dying, so audio.Play() doesnt work in my OnCollisionEnter() and OnDestroy() functions, i get this error :

Can not play a disabled audio source UnityEngine.AudioSource:Play()

But audio.Play() works in Start() and Update() functions. How can i fix this issue?Thanks!

My code:

public class SimpleEnemy : MonoBehaviour {

        public AudioClip explosionSound;
    	AudioSource Player;

    	void Start () 
    	{
    		Player = gameObject.AddComponent<AudioSource>();
    		Player.clip = explosionSound;
    		Player.volume = 1f;
    		Player.playOnAwake = false;
    		Player.loop = false;  	
    	}
    	
    	void OnDestroy()
    	{
    	      Player.Play();    
    	}
    	void OnCollisionEnter()
        { 
              Player.Play();
        }
}

The error seems pretty obvious – can’t play disabled sounds. For OnDestroy, you have to know the sound comes from the object. So OnDestroy can never play a sound (well, for 1/2 a frame.)

You could spawn an empty with the explosion sound (that destroys itself when done,) or have the explosion particle emitter also have a sound it plays. Or if all explosions sound the same (like a 2D game,) then have the player make the sound.

The usual way to have an AudioSource is just to click-create it. Making in Start should be the same, but you might want to check settings, and try it the other (manually add it beforehand) way.

Your Audio is being deleted before it can be played, since it is attached to a gameObject that gets destroyed before it can play the sound. Two things you could do

  • a) Use the static function
    PlayClipAtPoint (and pass it the
    position of the gameObject). That function automatically cleans-up the audio source after it has finished playing
  • b) Find the length of the sound clip and
    simply “wait” (put in a “yield”) for
    that duration, and then destroy the
    gameObject.