Basically I have a trigger and I want to play a sound upon entering it… 5 seconds later I want to play a different sound… but I cant seem to get WaitForSeconds to work in C#. Any suggestions?
Thanks, heres my code.
using UnityEngine;
using System.Collections;
public class PlaySound : MonoBehaviour {
public AudioSource vOne;
public AudioSource vTwo;
public bool played;
void OnTriggerEnter(Collider other) {
if (played != true)
{
played = true;
vOne.Play();
StartCoroutine(Example());
vTwo.Play();
}
}
IEnumerator Example() {
yield return new WaitForSeconds(5);
}
}
When you call StartCoroutine(), it runs through a single iteration of your coroutine and then moves to the next line of code, in this case vTwo.Play. If you want to play vTwo after the coroutine is finished, move it under the “yield return new WaitForSeconds(5)” line. Each frame, Example will be called, and it will continue yielding inside the WaitForSeconds(5) method and finally move to the lines below that after 5 seconds. The point of the coroutine is to allow small segments of code to be run between frames without halting the main thread. If OnTriggerEnter were an IEnumerator, you could yield the StartCoroutine(Example()) which would wait for Example to finish before moving to the next line, but it’s not in this case.
I am not very good with this, but from what I understand coroutines are threads (…ish).
They are exectuted simultaneously as other parts of the program. When you start the coroutine you make a thread that waits for 5 seconds and then does nothing.
A way to solve this would be putting the sounds inside the end of the coroutine;
IEnumerator Example() {
vOne.play();
yield return new WaitForSeconds(5);
vTwo.play();
}
I would love if anyone let me know if i am wrong in this.