I'm making a quiz in unity. I want for an audio to play when clicking on the right answer. Although the line code of playing the audio is before that of thread.Sleep(), when playing the quiz, it sleeps before enabling the audio!! I'll appreciate any help. Thanks in advance.
public void OnMouseDown()
{
checkAnswer();
}
public void checkAnswer()
{
if (Correct == true)
{
audioo = this.gameObject.GetComponent<AudioSource>();
audioo.enabled = true;
Thread.Sleep(5000);
NextQuiz.SetActive(true);
CurrentQuiz.SetActive(false);
}
else
{
}
}
I assume that unity is playing the audio after it stops sleeping? In which case why not simply use coroutines? Something like:
public void OnMouseDown(){
{
CheckAnswer();
}
public void CheckAnswer();
{
if (Correct == true)
{
audioo = this.gameObject.GetComponent<AudioSource>();
StartCoroutine(PlaySound(audioo));
}
else
{
}
}
IEnumerator PlaySound(AudioSource sound)
{
//Play the sound here, then load up the next question.
audioo.enabled = true;
yield return new WaitForSeconds(5f);
NextQuiz.SetActive(true);
CurrentQuiz.SetActive(false);
}
Additionally, you can also replace constantly deactivating and reactivating the audio source on your object, by simply creating 2 AudioClip variables and assigning a correct sound to one, as well as an incorrect sound to the other, then using audioo.Play(clipName) in order to play the appropriate one, like so:
public AudioClip correctSound;
public AudioClip incorrectSound;
public void OnMouseDown(){
{
CheckAnswer();
}
public void CheckAnswer();
{
if (Correct == true)
{
audioo = this.gameObject.GetComponent<AudioSource>();
StartCoroutine(PlaySound(audioo, correctSound));
}
else
{
}
}
IEnumerator PlaySound(AudioSource audioSource, AudioClip audioClip)
{
//Play the sound here, then load up the next question.
audioSource.Play(audioClip);
yield return new WaitForSeconds(5f);
NextQuiz.SetActive(true);
CurrentQuiz.SetActive(false);
}
Try something like that