Audio Source Play On Collision 2D?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoinCollect : MonoBehaviour {

public GameObject coin;
public AudioSource coinc;

void OnTriggerEnter2D(Collider2D coll)
{
    if (coll.gameObject.tag == "PlayerTag")
    {

        coinc.Play();

        Destroy(coin);
        
    }
}
}

Hello! I looked everywhere for this and I couldn’t find it. I’m trying to play an Audio Source on collision (2D) but the audio won’t play. I know the function works, because the Game Object does get destroyed. However, the sound does not play. Can anyone help?

Thanks.

There’s a lot that might be going wrong, but one thing to check is the position of your audio source. By default, an AudioSource plays sound to your AudioListener based on its 3D position. If it’s too far away, you won’t hear it, even if it plays at max volume. Is your AudioListener attached to the camera or view (where the players ears will be), at a reasonable distance from the AudioSource?


Is your AudioSource attached to the coin? If so, as soon as that coin is destroyed, the AudioSource will be destroyed too. It only plays while it’s alive. To solve this issue, I like to have a special prefab just for my audio effects, like this:

// Have a prefab with an AudioSource set to playOnAwake.
// You should also add a script to this Prefab which calls Destroy() on its own gameObject when the SFX has stopped playing. You can wait until !isPlaying in its Update(), or you can start a coroutine in its Awake() if you want to be efficient.

 public GameObject soundEffectPrefab;

 void OnTriggerEnter2D(Collider2D coll)
 {
     if (coll.gameObject.tag == "PlayerTag")
     {
         var effect = Instantiate( soundEffectPrefab );
         effect.transform.position = transform.position;

         Destroy(coin);         
     }
 }

You can use [122960-soundeffect.zip|122960] to get started with an effect prefab.

Wait…is the audiosource on the coin? because if it is destroying the coin immediately after will definitely not work!!!

Did you assign a clip to audio source. if not then you can use this,

`
public GameObject coin;
public AudioSource coinc;
public AudioClip coinClip;

void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == “PlayerTag”)
{
coinc.clip = coinClip;
coinc.Play();
Destroy(coin);

 }

}`