Unity协程中出现意外的控制流(检测完成)

时间:2016-10-15 18:58:20

标签: c# unity3d coroutine

我有一个附加到Unity 5 GameObject的脚本,当用户单击按钮时,该脚本将对象旋转固定量。旋转在协程中完成,以便随着时间的推移顺利进行。

我想阻止用户执行同一对象的另一次旋转,直到第一次完成为止。为此,我添加了一个isRotating布尔值,当协同程序启动时设置为true,当协程完成旋转时设置为false。代码如下:

using UnityEngine;
using System.Collections;

public class ObjectScript : MonoBehaviour {

    private bool isRotating = false;

    /* Rotate the object 90 degrees around the x axis centered on the origin */
    IEnumerator RotateObject() {
        isRotating = true;

        var updateRotation = 0.0f; // amount to rotate this tick
        for (var totalRotation = 0.0f; totalRotation <= 90.0f; totalRotation += updateRotation) {
            updateRotation = 90.0f * (Time.deltaTime / 0.5f);
            if (totalRotation + updateRotation > 90.0f) {
                updateRotation = 90.0f - totalRotation;
            }
            transform.RotateAround (Vector3.zero, Vector3.right, updateRotation);
            yield return null;
        }

        isRotating = false; // This line is never reached
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.X) && !isRotating) {
            StartCoroutine (RotateObject());
        }
    }
}

我的问题是永远不会到达isRotating = false行,所以即使在协程旋转完对象后,isRotating也会设置为true。 (我通过在行上放置调试断点来检查这一点,这些断点从未被命中)。因此,一旦对象旋转一次,它将永远不会再旋转。

为什么控制永远不会到达循环体外的线?

2 个答案:

答案 0 :(得分:2)

updateRotation = 90.0f - totalRotation;

=&GT; totalRotation + updateRotation = 90

每次totalRotation + updateRotation > 90.0f您重新分配updateRotation以便下一次迭代totalRotation + updateRotation = 90

=&GT; totalRotation <= 90.0f永远不会false

答案 1 :(得分:1)

我发现了错误。

RotateObject内的主循环中,我正在检查条件totalRotation <= 90.0f。但是,我已经在循环中添加了代码以确保我没有过度旋转:

if (totalRotation + updateRotation > 90.0f) {
    updateRotation = 90.0f - totalRotation;
}

这可以很好地防止过度旋转,但是因为我通过添加totalRotation来更新循环变量updateRotation

    for (...; ...; totalRotation += updateRotation) {

totalRotation基本上是“钳制”的,永远不会超过90.0f - 因此循环永远不会退出。

所以,修复方法是将我的循环条件更改为<而不是<=,如:

for (var totalRotation = 0.0f; totalRotation < 90.0f; totalRotation += updateRotation) {