使用do while循环冻结统一

时间:2018-06-02 11:03:03

标签: c# unity3d

所以我想让我的木板从 A 点到 B ,然后在它到达B时停止。我实施了do while loop,{{1}但不幸的是,每当我点击播放场景按钮时,团结冻结,任何想法为什么会发生这种情况?

for-loop

2 个答案:

答案 0 :(得分:4)

你的do while循环每次都会执行Rigidbody2d.velocity = new Vector2(1f, 0f);。在这个循环中没有任何东西可以改变。如果你这样做了:

while (x < y)
{
    a = 5;
    x++;
}

这样做不会有任何意义。简单地a = 5将具有相同的效果,只是更少的不受欢迎的循环。

除此之外,您根本不会更改x的值。这是造成这个问题的原因。你基本上在做

while (x < y)
    a = 5;

如果x在开始时小于y,则x将始终小于y,因此它将继续执行while的正文永远循环,因此Unity陷入Update方法。

这与与每帧调用Update的事实有关。这只是一个简单的无限循环,它是由使用不变化的条件引起的。即使它处于不同的功能,这也会阻止该程序。

这是你可以做的事情:

// Using a property will always return the targets X value when called without having to 
// set it to a variable
private float X 
{ 
    // Called when getting value of X
    get { return Rigidbody2d.transform.position.X; } }  

    // Called when setting the value of X
    set { transform.position = new Vector2(value, transform.position.y); }  
}
private bool isMoving = false;

private void Update () 
{  

    if (X < -4 && !isMoving)
    { 
        Rigidbody2d.velocity = new Vector2(1f, 0f); // Move plank till it reaches point B
        isMoving = true;
    }
    else if (isMoving) 
    { 
        Rigidbody2d.velocity = new Vector(0f, 0f);  // You probably want to reset the 
                                                    // velocity back to 0
        isMoving = false;
    }                                               
} 

答案 1 :(得分:2)

正如Update-method上面的注释所示,每帧调用一次Update()。 while循环将阻止Update()直到条件满了,但是当你阻塞Update()方法时它永远不会被实现。

尝试这样的事情

void Update() 
{
     if(this.transform.position.x < -4) 
          Rigidbody2d.velocity = new Vector2(1f, 0f);
}

想象一下,团结中的游戏环看起来像这样(非常简化)

while(running) 
{
   // Start of frame
   CallUpdateOnGameObjects();
   ProcessPhysics(); // this is where the rigidbody is moved
   DrawEverything();
   // End of frame
}

因此,当你的update方法被调用时,你正在开始你的while循环,但是while循环的条件永远不会被填满,因为gameloop永远无法访问ProcessPhysics()。

供参考,请参阅 https://docs.unity3d.com/Manual/ExecutionOrder.html