猿问

使用 do while 循环冻结统一

所以我想让我的木板从A点移动到B点,然后在它到达 B 点时停止。我实现了do while loop,for-loop但不幸的是,每次我点击播放场景按钮时,Unity 都会冻结,知道为什么会发生这种情况吗?


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

    } 

}


慕运维8079593
浏览 165回答 1
1回答

倚天杖

你的 do while 循环Rigidbody2d.velocity = new Vector2(1f, 0f);每次都会执行。该循环中没有任何变化。如果你这样做:while (x < y){&nbsp; &nbsp; a = 5;&nbsp; &nbsp; x++;}这样做没有任何意义。只是a = 5会产生相同的效果,只是少了很多不必要的循环。最重要的是,您根本没有改变 的价值x。这就是导致问题的原因。你基本上在做while (x < y)&nbsp; &nbsp; 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&nbsp;// set it to a variableprivate float X&nbsp;{&nbsp;&nbsp; &nbsp; // Called when getting value of X&nbsp; &nbsp; get { return Rigidbody2d.transform.position.X; } }&nbsp;&nbsp;&nbsp; &nbsp; // Called when setting the value of X&nbsp; &nbsp; set { transform.position = new Vector2(value, transform.position.y); }&nbsp;&nbsp;}private bool isMoving = false;private void Update ()&nbsp;{&nbsp;&nbsp;&nbsp; &nbsp; if (X < -4 && !isMoving)&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Rigidbody2d.velocity = new Vector2(1f, 0f); // Move plank till it reaches point B&nbsp; &nbsp; &nbsp; &nbsp; isMoving = true;&nbsp; &nbsp; }&nbsp; &nbsp; else if (isMoving)&nbsp;&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Rigidbody2d.velocity = new Vector(0f, 0f);&nbsp; // You probably want to reset the&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // velocity back to 0&nbsp; &nbsp; &nbsp; &nbsp; isMoving = false;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;
随时随地看视频慕课网APP
我要回答