- Home /
How to play sound on destroy (Unity2D)
I am making a 2d game and it has coins and when the player touches the coin I am trying to make the coin disappear and make a ding sound .the problem is that the coin disappears but no sound.
using UnityEngine;
using System.Collections;
public class coins : MonoBehaviour {
static int coin = 0;
AudioClip coinSound;
void Start()
{
coin = 0;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
coin++;
audio.PlayOneShot(coinSound);
StartCoroutine(Ding());
Destroy(this.gameObject);
}
}
void OnDisable(){
PlayerPrefs.SetInt ("coin", coin);
}
IEnumerator Ding(){
yield return new WaitForSeconds (0.4F);
}
}
Answer by VoidChimera · Jan 02, 2015 at 06:23 AM
You could have another object play the sound, I think the problem is that it's starting the sound clip, but then destroying itself, stopping it. You could have a SoundManager gameobject and just have your other stuff play sounds through that instead, so you don't have to worry about other stuff interfering with it.
Answer by Arahan Imon · Jan 02, 2015 at 06:23 AM
Make Sure that you must have at least one audio source component attached to your scene.
oh! Audio Clip variable is not public so where are you passing you clip to play,check out your code once again . AudioClip coinSound;here make AudioClip public and pass your audio file to play.
Answer by Ekta-Mehta-D · Jan 02, 2015 at 06:31 AM
Hii..
Your code has problem.
This script contains code to play sound as well as it is destroying the object to which this script is attached.
So your sound does not play as the object get destroyed and script will no more active in the scene.
I think you should attach this script to player and have trigger/collision code as well as destroy coin code in that script.
Thanks..