简体   繁体   中英

How to play sound on destroy

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);
       }
}

You need to delay the destruction so that you can actually play the sound, since they happen in the same object.

void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Player")
    {
        coin++; 
        StartCoroutine(Ding());  
    }
}

IEnumerator Ding()
{
    audio.PlayOneShot(coinSound);
    yield return new WaitForSeconds(5);
    Destroy(gameObject);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM