Getting audio to play on item pickup in Unity

Viewed 122

I'm trying to play a sound effect when I pick up an item. I have the audio source component, and I have the sound clip assigned. I get no errors and everything seems to be working, but I still do not get sound when I pick up the item. My script:

    public ParticleSystem pickupEffect;

public float speedPercentDrop = 50f; // 10% chance
public GameObject speedPowerUp;

public float healthPercentDrop = 70f; // 70% chance
public GameObject healthPowerUp;

private AudioSource puAudio;

public void Start()
{
    
}

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        Instantiate(pickupEffect, transform.position, transform.rotation);
        puAudio = GetComponent<AudioSource>();
        puAudio.Play();
        Pickup(other);
        
    }
}

void Pickup(Collider player)
{
    
    Debug.Log("Picked Up");
    Destroy(gameObject);


}
1 Answers

There is no need to delay your object destroying.

  1. Create an empty object as the item child
  2. Attach your audio to the child
  3. Before destroying the item, change the child parent to null => transform.GetChild(0).transform.parent = null;

So in the end, your "PickUp" method should look like this:

void Pickup(Collider player)
{
    Debug.Log("Picked Up");
    Transform _child = transform.GetChild(0);
    _child.GetComponent<AudioSource>().Play();
    _child.parent = null;
    Destroy(gameObject);
}
Related