【问题标题】:How to prevent an interruption to a Coroutine that causes it to restart/repeat itself in Unity?如何防止 Coroutine 中断导致它在 Unity 中重新启动/重复自身?
【发布时间】:2018-04-20 18:21:16
【问题描述】:

在我的项目中,我有一个对象和一些按钮。当我按下其中一个按钮时,对象会在协程中进行新的旋转。当用户在协程有机会第一次完成该方法之前按下按钮时,就会出现该错误。在这种情况下,它基本上会重新启动从开始旋转到新旋转的 slerp 运动。有没有办法防止这种情况发生?我可以使用布尔值来检查协程是否仍处于 slerp 的中间,但是理想的解决方案是在它所在的位置停止 slerp,然后 slerp 到新的旋转。下面是我在按钮上使用的协程:

public IEnumerator SlerpRotation(Transform trans, Quaternion slerpTo)
{
        timer = 0;
        Quaternion rotation = trans.localRotation;
        while (timer < 2)
        {
            trans.localRotation = Quaternion.Slerp(rotation, slerpTo, timer/2f);
            timer += Time.deltaTime;
            yield return null;
        }
}

在我使用这种方法之前,我有另一种方法,它基本上只是检查它是否等于其他两个角度并在两个角度之间切换。

【问题讨论】:

  • 如果当前有一个协程正在运行,您可以设置一个标志,然后取消该协程或在第一个协程完成时排队启动新的协程...

标签: c# unity3d


【解决方案1】:

您可以将Coroutine 保存到variable。每当您需要启动Coroutine 时,您可以先停止Coroutine,然后重新启动。像这样:

float timer;
Coroutine theCoroutine;

public void SlerpRot(){
    if (theCoroutine != null)
        StopCoroutine (theCoroutine);
    theCoroutine = StartCoroutine (SlerpRotation(this.transform,Quaternion.identity));
}
public IEnumerator SlerpRotation(Transform trans, Quaternion slerpTo)
{
    timer = 0;
    Quaternion rotation = trans.localRotation;
    while (timer < 2)
    {
        trans.localRotation = Quaternion.Slerp(rotation, slerpTo, timer/2f);
        timer += Time.deltaTime;
        yield return null;
    }
}

【讨论】:

  • 这正是我所需要的。我其实不知道你可以将协程保存到变量中哈哈
猜你喜欢
  • 2021-01-03
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
相关资源
最近更新 更多