当循环冻结游戏时 - 还有其他可以旋转对象的东西吗?

While loop freezes game - Is there anything else which can rotate an object?

我正在尝试为 TBS 游戏创建一个旋转光源,它会在回合结束时旋转。为此,我使用了事件;我有两个脚本,一个提前转弯:

public delegate void Time(int t);
public static event Time Time_Change;
public int t = 1;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Return))
    {
        t = t + 1;
        if (t > 8) { t = 1; }
        Debug.Log(t);
        if (Time_Change != null)
        {
            Time_Change(t);
        }
    }

(有八个 day/night 阶段)和一个接收信号并移动它所连接的灯的阶段:

public int angle = 85;

void Start () {
    Time_Controller.Time_Change += Move_Lights;
}


void Move_Lights(int t)
{

//phase detection, set angle variable

if (t % 2 == 0)
    {    
        //----------------------------------------       
        while (transform.eulerAngles.x != angle)
        {
            transform.Rotate(Vector3.right * Time.deltaTime, Space.World);
        }
        //----------------------------------------
    }
}

问题是,当我 运行 游戏并按下回车键时,一切都冻结了,关闭 Unity 的唯一方法是通过任务管理器(这也显示了 Unity CPU 使用率的峰值,同时游戏被冻结)。我已经通过消除过程(没有它一切正常)追踪到故障线是

while (transform.eulerAngles.x != angle)
{
    transform.Rotate(Vector3.right * Time.deltaTime, Space.World);
}

如上所述。我该怎么办?我已经尝试了各种旋转光源的方法,但还没有任何方法可以防止崩溃。

提前致谢。

我建议在这里使用协程。

void Move_Lights(int t)
{
    //phase detection, set angle variable

    if (t % 2 == 0)
    {    
        StartCoroutine(RotateLight());
    }
}

IEnumerable RotateLight()
{
    while (transform.eulerAngles.x != angle)
    {
        transform.Rotate(Vector3.right * Time.deltaTime, Space.World);
        yield return null;
    }
    yield break;
}

你的游戏卡住了,因为它陷入了你的不等式的无限循环。 while 循环仅在转换的浮点值等于 angle 时退出,由于浮点的精度,这实际上永远不会为真。当使用带浮点数的等式时,你应该对你的比较有一个公差。如果你正在寻找一个精确的角度,这当然不是你想要使用的方法。

// while the transforms angle is not within .5f of the desired...
while (Mathf.abs(transform.eulerAngles.x-angle) > .5f)
{
    transform.Rotate(Vector3.right * Time.deltaTime, Space.World);
    yield return null;
}