admin管理员组文章数量:1293048
I am coding a parkour game in unity and i want to code an elevator with a platoform, there is my function :
IEnumerator Wait()
{
yield return new WaitForSeconds(secondsToWait);
while (canGoUp && isDown && !isUp)
{
Debug.Log("entered");
transform.Translate(Vector3.forward * speed);
}
Debug.Log("Left");
}
Its a basic function, i want the platform to wait 3 seconds after he entered a trigger:
void OnTriggerEnter(Collider other)
{
canGoUp = true;
}
So when he go in the trigger he goes up but the problem is that every time i want to use a while loop my unity crashes.
Here is my update function where i change the bools :
void Update()
{
if (transform.position.y >= downPos)
{
isDown = true;
}
else if (transform.position.y <= upPos)
{
isUp = true;
}
if (canGoUp && isDown && !isUp)
{
StartCoroutine(Wait());
}
}
The positions are negatifs
I expeted that the elevater goes up,
I am coding a parkour game in unity and i want to code an elevator with a platoform, there is my function :
IEnumerator Wait()
{
yield return new WaitForSeconds(secondsToWait);
while (canGoUp && isDown && !isUp)
{
Debug.Log("entered");
transform.Translate(Vector3.forward * speed);
}
Debug.Log("Left");
}
Its a basic function, i want the platform to wait 3 seconds after he entered a trigger:
void OnTriggerEnter(Collider other)
{
canGoUp = true;
}
So when he go in the trigger he goes up but the problem is that every time i want to use a while loop my unity crashes.
Here is my update function where i change the bools :
void Update()
{
if (transform.position.y >= downPos)
{
isDown = true;
}
else if (transform.position.y <= upPos)
{
isUp = true;
}
if (canGoUp && isDown && !isUp)
{
StartCoroutine(Wait());
}
}
The positions are negatifs
I expeted that the elevater goes up,
Share Improve this question asked Feb 12 at 23:43 Crucial BeautyCrucial Beauty 131 silver badge1 bronze badge 1 |1 Answer
Reset to default 5The while loop is looping infinitely without progressing to the next frame. Nothing in update can execute because the main thread is stuck in the while loop.
You need to yield something to allow the main thread to progress.
while (canGoUp && isDown && !isUp)
{
Debug.Log("entered");
transform.Translate(Vector3.forward * speed);
yield return null; // <-- resume after one frame
}
本文标签: cWhile loop crashing every timeStack Overflow
版权声明:本文标题:c# - While loop crashing every time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741570342a2385971.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
while
loop you got there .. how is the condition supposed to change within the loop? I guess you would have wanted toyield return null;
within the loop in order to only have one iteration each frame ... Note though: you still will also want to check whether a routine is already running .. otherwise you might start a new one every frame – derHugo Commented Feb 13 at 6:01