簡體   English   中英

如何在 10 秒后停止協程?

[英]How can I stop the Coroutine after 10 seconds?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlendShapesController : MonoBehaviour
{
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool randomizeNumbers = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
        //StartCoroutine(RandomNumbers());

        StartCoroutine(AnimateMouth());
    }

    // Update is called once per frame
    void Update()
    {
        //AnimateMouth();

        if(randomizeNumbers == true)
        {
            //StartCoroutine(RandomNumbers());

            randomizeNumbers = false;
        }
    }

    IEnumerator RandomNumbers()
    {
        int rand = Random.Range(0, 23);
        bodySkinnedMeshRenderer.SetBlendShapeWeight(0, rand);

        yield return new WaitForSeconds(0.3f);

        randomizeNumbers = true;
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    private bool talking = true;
    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (talking)
        {
            //yield return StartCoroutine waits for that coroutine to finish before continuing
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration)); 
        }

        yield return new WaitForSeconds(10);

        talking = false;
    }
}

在底部,它在說話時進行了一個 while 循環是真的。 我希望 10 秒后談話將是假的或停止協程。

我試過這個:但它什么也沒做,while循環仍在工作,說話仍然是真的。

yield return new WaitForSeconds(10);
    
talking = false;

設置一個截止日期,而不是用於談話的布爾值,例如一個日期/時間戳,說明談話的時間。

public IEnumerator AnimateMouth()
{
    var talkUntil = DateTime.Now.AddSeconds(10);

    while (DateTime.Now < talkUntil)
    {
        yield return StartCoroutine(LerpShape(0, valueRange, duration));
        yield return StartCoroutine(LerpShape(valueRange, 0, duration)); 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM