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,
The 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
}