abs abs - 30 days ago 13
C# Question

audio.PlayOneShot doesn't work in Unity

I want my game to play sound when a player collides with coin, but the sound doesn't play. I don't receive any errors. I attached sound to Audio Source and script in Unity.

using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class TriggerCoin : MonoBehaviour
{

//TODO
//Counter of collected coins

public AudioClip coinSound;
new AudioSource audio;

void Start()
{
audio = GetComponent<AudioSource>();
}


void Update()
{

}

void OnTriggerEnter2D(Collider2D other)
{
GameObject gObj = other.gameObject;

if (gObj.CompareTag("Player"))
{
Debug.Log("You picked up coin!");
audio.PlayOneShot(coinSound, 0.8f);
Destroy(gameObject);
}
}
}

Answer Source

See the problem below:

audio = GetComponent<AudioSource>(); shows that the AudioSource is attached to this script or GameObject this script(TriggerCoin) is attached to.

Then you play the audio: audio.PlayOneShot(coinSound, 0.8f);

And destroy the GameObject the immediately: Destroy(gameObject);.

The destroyed GameObjbect is holding the AudioSource too so it will take AudioSource with it to die.

Solution:

Attach the AudioSource to an empty GameObject that does not destroy. Let's call it "AudioHolder" then find it an play the audio.

GameObject obj = GameObject.Find("AudioHolder");

AudioSource aud = obj.GetComponent<AudioSource>();

aud.PlayOneShot(coinSound, 0.8f);

Note:

Remove the new AudioSource audio; and rename audio to something else. It's a good idea to do that.