Jeremy McCloud
Jeremy McCloud

Reputation: 163

How do I delay an audio clip in Unity?

I've just started programming in Unity and what I'd like to do is to delay an audio clip to play by 5 seconds after the game starts.

I've searched online and found this code here, but when I execute it there is no sound.

using UnityEngine;
using System.Collections;

public class WizardVoice : MonoBehaviour {
    public AudioSource myAudio;
    // Use this for initialization
    void Start () {

        StartCoroutine(PlaySoundAfterDelay(myAudio, 300.0f));
    }

    // Update is called once per frame
    void Update () {

    }

    IEnumerator PlaySoundAfterDelay(AudioSource audioSource, float delay)
    {
        if (audioSource == null)
            yield break;
        yield return new WaitForSeconds(delay);
        audioSource.Play();
    }

}

I'm trying to find out what I did wrong, but not having any luck. Any help is appreciated!

Thank you!

Upvotes: 1

Views: 6630

Answers (1)

Programmer
Programmer

Reputation: 125275

Change 300.0f to 5000f because 300.0f is 300 milliseconds and not 5 seconds. 1000f = 1 second. Use 5000f for 5 seconds.That's how WaitForSeconds(); work.

Upvotes: 0

Related Questions