c# - 使用 do while 循环冻结统一
问题描述
所以我想让我的木板从A点到B点,然后在它到达B点时停止。我实施了do while loop
,for-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
}
}
解决方案
你的 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;
}
}
推荐阅读
- graphql - GraphQL:探索没有通配符 (*) 的 API?
- javascript - 如何从容器更新组件的状态?
- vb.net - 拖放不适用于快捷方式或exe文件
- jenkins - Jenkins Bitbucket Notifier 使用管道时不通知
- flutter - Flutter Firebase上市时收到的错误
- node.js - WebStorm 已将目录中的所有文件标记为非项目文件
- mongodb - how to set a new property on existing records in mongoDB atlas
- python-3.x - 如何读取/读取包含具有完全不同模式的文件的目录
- scala - 线程“主”java.lang.NoClassDefFoundError 中的异常:org/apache/log4j/or/RendererMap
- python - 将包含 Python 代码(由 reticulate 启用)的 Rmarkdown 文件部署到 shinyapp.io