Can Not Play An Audio Source Even Though It Plays On Awake

Hello,

Let me start off by saying yes, I know, there are a ton of other questions about this, but none of them have solved my problem.

Anyways, I have a prefab with an AudioSourcce component. It plays the sound on Awake, but whenever it is called through scripts, it doesn’t play sound, but instead give a “Can not play a disabled audio source” warning.

Here is how it is called:

if (Input.GetMouseButtonDown (0)) {
	CurrentWeapon.GetComponent<Weapon> ().Fire ();
}

And here is the Fire() method:

public void Fire () {
	GetComponent<AudioSource> ().clip = FiringSound;
        GetComponent<AudioSource>().Play();
}

I ran into the same problem today and noticed after a while, that I destroy the gameobject in the function, where I play the audio.

My conclusion was, that the gameobject gets destroyed, before the audio is played, even though my call for playing the audio came before destroying the object:

        AudioSource blockDestroyedSound = GetComponent<AudioSource>();
        blockDestroyedSound.Play();

        Destroy(gameObject);

The solution for this was to play the audio in a coroutine and destroy the gameobject after the audio was finished playing:

private IEnumerator PlaySoundAndDestroyAfterwards()
    {
        AudioSource blockDestroyedSound = GetComponent<AudioSource>();
        blockDestroyedSound.Play();

        while (blockDestroyedSound.isPlaying)
        {
            yield return null;
        }

        Destroy(gameObject);
    }

@TheDogePwner

Is the AudioSource on the same object as the Weapon component?

Is CurrentWeapon a reference to the prefab itself, or the instantiated prefab?

Click Add Component > Audio > Audio Listener.You HAVE to have a audio listener in order to play the sound.

Also the Script,Audio Listener and Audio Source are in the same object.

Hope it works

Does the prefab have the audiosource enabled?
Is the AudioSource attached to the same object the script is attached to (i.e. not a child of the object the script is attached to)?

Try modifying your Fire() method as follows for testing:

public void Fire () {
      Debug.Log( "Enabled: " + GetComponent<AudioSource> ().enabled);
     GetComponent<AudioSource> ().clip = FiringSound;
         GetComponent<AudioSource>().Play();
 }

Also, on a side note… Try storing a reference to your AudioSource in a variable. In most cases you should only be using GetComponent on any given component once (when you know you’re going to use it more than once).

It’s more expensive to use GetComponent every time you reference a component than to store it in a variable and do it that way.