Audio doesn't play when collecting a coin

Hello!

I want the game to play a sound when the player collects a coin, but the sound doesn’t play. What am I doing wrong?

public GameObject Coin;
public AudioClip soundFile;

    void OnTriggerEnter ()
    		{
    				if (Coin.gameObject.tag == "Coin") {
    						CoinController.coins++;
    						CoinController.coinsCollectedThisLevel++;
    						PlayerPrefs.SetInt ("Coins", CoinController.coins + 1);
    						audio.clip = soundFile;
    						audio.Play();
    						Destroy (Coin.gameObject);
    				}
    		}

Hi,
i think Broxxar already found the Problem. You play the clip and destroying the object at the same time. The audio reference returns the AudioSource of the gameObject.

Try to call destroy with the delay of the length of your audio clip.

Destroy(Coin.gameObject,audio.clip.length);

Boxxar has found your problem, But here’s another solution:

Replace

audio.Play();

with

 AudioSource.PlayClipAtPoint(audio, Coin.transform.position);

This creates a seperate game object that is a sound source but has no body and self destructs after the audio clip is over.

This is better assuming the object has a collider and you don’t wish for an animation to play.

When you have an animation it is better to use

Destroy(Coin.gameObject, YourAnimationObjectHere.clip.length)

I got the idea from Unity Connect

You shold do the stealth tutorial if you haven’t already.