Can not play a disabled audio source.

I have no idea why this is not working, I have attached the script and audiosource to the same game object.

using UnityEngine;

public class CoinPickup : MonoBehaviour
{
    public int coinValue = 1;

    GameObject player;
    AudioSource collectClip;

    void Awake ()
    {
        collectClip = GetComponent <AudioSource> ();
    }

    void Start () {
        player = GameObject.FindGameObjectWithTag ("Player");
    }

    void OnTriggerEnter (Collider other)
    {
        // If the entering collider is the player...
        if(other.gameObject == player)
        {
            ScoreManager.score += coinValue;
            Destroy(gameObject);
            // Play the collect sound effect.
            collectClip.Play ();
        }
    }
}

I’ve tried this too, still the same :frowning:

using UnityEngine;
using System.Collections;

public class CoinPickup : MonoBehaviour
{
    public int coinValue = 1;
 
    GameObject player;
    public AudioClip impact;
 
    void Start () {
        player = GameObject.FindGameObjectWithTag ("Player");
    }
 
    void OnTriggerEnter (Collider other)
    {
        // If the entering collider is the player...
        if(other.gameObject == player)
        {
            ScoreManager.score += coinValue;
            Destroy(gameObject);
            // Play the collect sound effect.
            GetComponent<AudioSource>().PlayOneShot(impact, 0.7F);
        }
    }
}

The box is ticked in the inspector.

Still can’t find a solution :confused:

you are trying to play the sound after destroying the gameObject the script is attached to… change the code to this

// If the entering collider is the player...
      if(other.gameObject == player)
     {
          ScoreManager.score += coinValue;
GetComponent<AudioSource>().PlayOneShot(impact, 0.7F);
         Destroy(gameObject);
         // Play the collect sound effect.
         
       }

Also you will have to put the AudioSouce on a gameobject that isn’t being destroyed

If the target game object is destroyed or disabled you can use AudioSource.PlayClipAtPoint, which internally just creates a game object holding an audio source to play your sound with, destroying it when it is done.

2 Likes