Play a sound with a delay

Hi !

Anyone know how could I play a sound in my project with a delay of 10s ?

Thanks :slight_smile: !

1 Like

Use a coroutine:

IEnumerator playSoundAfterTenSeconds()
{
  yield return new WaitForSeconds(10);
  audiosource.Play();
}

// then elsewhere when you want to invoke it:

void someOtherMethodInAMonoBehaviour()
{
  StartCoroutine(playSoundAfterTenSeconds());
}

or even:

IEnumerator playSoundWithDelay(AudioClip clip, float delay)
{
  yield return new WaitForSeconds(delay);
  audiosource.PlayOneShot(clip);
}

// then elsewhere when you want to invoke it:

void someOtherMethodInAMonoBehaviour()
{
  StartCoroutine(playSoundWithDelay(clipToPlay, delay));
}

Hope that helps.

1 Like

The PlayDelayed() function on the AudioSource component should do the trick.

AudioSource audioSource = GetComponent<AudioSource>();
audioSource.PlayDelayed( 10 );
9 Likes

Well then, who’s a smarty bum!

:slight_smile:

The Unity Code Reference is your friend. :slight_smile: Always search there first. I use it dozens of times daily.

Thank you for your answers. But I have another problems with your codes :

In factm I dont know how to make a script and everytime, in every scriptm I have problems, even I copy and paste from a script I have found on internet :confused: …

1 Like

Finaly I have created a delay on my sound with Audacity and it’s ok ^^

How would I make it so I can change the seconds in the inspector instead of adjusting it in the script every time?

public float delay;

AudioSource audioSource = GetComponent<AudioSource>();
audioSource.PlayDelayed(delay);
1 Like

Just in case, PlayDelayed does not respect Time.timeScale, so it may become a problem if you change time scale (e.g. in pause menu)

Hi
i tried the above code but it is not working. The code is correct. No errors are displayed on the console but the code is not getting implemented

5431593--553098--Screenshot 2020-02-01 at 12.37.34 PM.png

This is coming in the inspector view but the code is not getting implemented in the file