C# 使用线程。睡眠(1000);统一体
我在unity做测验。我想在点击正确答案时播放音频。虽然播放音频的行代码在thread.Sleep之前,但在播放测验时,它会在启用音频之前休眠!!我将感谢任何帮助。提前谢谢C# 使用线程。睡眠(1000);统一体,c#,unity3d,thread-sleep,C#,Unity3d,Thread Sleep,我在unity做测验。我想在点击正确答案时播放音频。虽然播放音频的行代码在thread.Sleep之前,但在播放测验时,它会在启用音频之前休眠!!我将感谢任何帮助。提前谢谢 public void OnMouseDown() { checkAnswer(); } public void checkAnswer() { if (Correct == true) { audioo = this.g
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
{
}
}
音频播放发生在主线程上,Unity主要是单线程的,您的代码使当前的主线程进入睡眠状态,因此直到线程从睡眠中醒来,音频才会播放
为解决此问题,您可能需要考虑使用。启动将返回新WaitForSeconds5的协同程序;然后开始下一个测验。
我假设unity在停止睡眠后播放音频?在这种情况下,为什么不简单地使用协程呢?比如: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);
}
此外,您还可以通过简单地创建2个AudioClip变量并为其中一个变量指定正确的声音,为另一个变量指定不正确的声音,然后使用audioo.PlayclipName播放相应的声音,来替换不断停用和重新激活对象上的音频源,如下所示:
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);
}
试试那样的