Give yield less than 1 second.

How to give waitforseconds less than 1, because my coin get’s destroyed to fast and doesn’t plays the sound.

public class Coin : MonoBehaviour {

    public AudioSource coinAudio;

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

    IEnumerator OnTriggerEnter(Collider Player)
    {
        UIManager.score += 1;
        coinAudio.Play();
        yield return new WaitForSeconds (1);
        Destroy(gameObject);

    }

}

yield return new WaitForSeconds (0.5f) to wait for half a second.

Less than 1?

Well… than it’d be like 0.5f, or 0.1f, if you wanted less than 1 second.

Though… you’re saying that the sound doesn’t have enough time to play. So why would you want it to be less, wouldn’t you want more time before you destroy the gameObject?

Why don’t you play as long as the clip is?

    IEnumerator OnTriggerEnter(Collider Player)
    {
        UIManager.score += 1;
        if(coinAudio.clip != null)
        {
            coinAudio.Play();
            yield return new WaitForSeconds (coinAudio.clip.length);
        }
        Destroy(gameObject);

    }
1 Like

My understanding was that the OP had implemented the coroutine to add a delay to prevent destroying the audio as soon as it started playing. I might be wrong though.

However, rather than waiting for a fixed amount of time it would probably be better to get the clip length and use that as the value of the waitforseconds.

1 Like

This did the trick for me, ty!