首页 > 解决方案 > 使用 do while 循环冻结统一

问题描述

所以我想让我的木板从A点到B点,然后在它到达B点时停止。我实施了do while loopfor-loop但不幸的是,每次我点击播放场景按钮时统一冻结,知道为什么会发生吗?

public class movingplank : MonoBehaviour 
{
    public Rigidbody2D Rigidbody2d;        
    float x;   
    Vector2 ve = new Vector2();

    // Use this for initialization
    void Start () 
    {
        Rigidbody2d = GetComponent<Rigidbody2D>();
    }

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


        do 
        {   ve = Rigidbody2d.transform.position;
             x = ve.x;      // storing x component of my plank into float x 
           Rigidbody2d.velocity = new Vector2(1f, 0f);
        } while (x <-4);   // move plank till it reaches point B
    } 
}

标签: c#unity3d

解决方案


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

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

这样做没有任何意义。只是a = 5会产生相同的效果,只是少了很多不需要的循环。

最重要的是,您根本没有改变的价值x。这就是造成问题的原因。你基本上在做

while (x < y)
    a = 5;

如果一开始x就小于yx就会一直小于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;
    }                                               
} 

推荐阅读