在检测到每个新的可跟踪项后,我如何重置Coroutine

本文关键字:Coroutine 何重置 跟踪 检测 | 更新日期: 2023-09-27 18:30:00

科罗廷需要在20秒后或检测到新的可跟踪时重置

IEnumerator VoicePrompt()
        {
            yield return new WaitForSeconds (20f);
            FindTheCard.Play ();
            currentPointSound.GetComponent<AudioSource> ().PlayDelayed (2.3f);
        } 

在检测到每个新的可跟踪项后,我如何重置Coroutine

通过使用InvokeRepeating和CancelInvoke,您可以执行以下操作:

在启动/唤醒方法中:

void Start(){
    ...
    // Start the repetition by calling the InvokeRepeating
    // 2nd argument (0f) is the delay before first invocation
    // 3rd argument (20f) is the time between invocations
    InvokeRepeating("VoicePrompt", 0f, 20f);
    ...
}

然后在碰撞方法中:

void OnCollisionEnter(Collision collision){
    ...
    // Cancel the invoke to 'reset' it
    CancelInvoke("VoicePrompt");
    // And start it again
    InvokeRepeating("VoicePrompt", 0f, 20f);
    ...
}

我不知道什么是可跟踪的,但如果你想使用Coroutine,那么你可以在Coroutine中使用flag,当你检测到新的可跟踪时,将标志更改为True:

bool isNeedToRun = true;
IEnumerator flagChangeCounter()
{
    While (true)
    {
        isNeedToRun = true;
        yield return new WaitForSeconds (20f);
    }
}    
IEnumerator VoicePrompt()
{
    While (true)
    {
        While (!isNeedToRun)    //Loop until (isNeedToRun == true)
        {
           yield return new WaitForSeconds (0.1f);
        }
        FindTheCard.Play ();
        currentPointSound.GetComponent<AudioSource> ().PlayDelayed (2.3f);
        isNeedToRun = false;
    }
} 
// And change the 'isNeedToRun' value to 'true' when you detect new trackable

这是代码和协同程序下面的OnTrackingFound():

private IEnumerator Countdown(int time){
                while(time>0){
                    Debug.Log(time--);
                    yield return new WaitForSeconds(1);
                }
                FindTheCard.Play ();
                currentPointSound.GetComponent<AudioSource> ().PlayDelayed (2.3f);
                Debug.Log("Countdown Complete!");
            }
    public void OnTrackingFound()
            {
                show.SetActive (true);
                Renderer[] rendererComponents = GetComponentsInChildren<Renderer> (true);
                Collider[] colliderComponents = GetComponentsInChildren<Collider> (true);
                AudioSource[] audiocomponents = GetComponentsInChildren<AudioSource> (true);
                StartCoroutine ("Countdown", 20);       
          }