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.
public class TriggerCoin : MonoBehaviour
//Counter of collected coins
public AudioClip coinSound;
new AudioSource audio;
audio = GetComponent<AudioSource>();
void OnTriggerEnter2D(Collider2D other)
GameObject gObj = other.gameObject;
Debug.Log("You picked up coin!");
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:
And destroy the GameObject the immediately:
The destroyed GameObjbect is holding the
AudioSource too so it will take
AudioSource with it to die.
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);
new AudioSource audio; and rename audio to something else. It's a good idea to do that.