- Home /
While Loop crashing Unity consistently
I'd like this function to lerp from 0 to 1 and then exit, as opposed to running for a single frame then exiting. As you can see, I've tried wrapping Mathf.Lerp in a while() loop. However, this consistently crashes Unity. How else could I go about achieving this same effect?
static function fadeIn(fadeSpeed : float)
{
// Fades from black to opaque
Debug.Log("Made it here");
alpha = 1;
while(alpha > 0)
{
alpha = Mathf.Lerp(1, 0, fadeSpeed * Time.deltaTime);
Debug.Log("In the while function");
}
}
Answer by Statement · Mar 07, 2011 at 02:08 AM
You'll get an endless loop where alpha always stays at a fixed value between 1 and 0, unless fadeSpeed * Time.deltaTime
happens to become 1.
What you probably want to use is a coroutine and modify your Mathf.Lerp to Mathf.MoveTowards instead.
function fadeIn(fadeSpeed : float)
{
alpha = 1;
while(alpha > 0)
{
alpha = Mathf.MoveTowards(alpha, 0, fadeSpeed * Time.deltaTime);
yield;
}
}
Then you can call your coroutine like so:
StartCoroutine(fadeIn(2));
Your answer
![](https://koobas.hobune.stream/wayback/20220613111644im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Iterator variable not increasing. 1 Answer
While/if loop problem 1 Answer
How to get something to be inactive while there is a certain value 2 Answers
Display a loading while processing a while loop 1 Answer
While loop freezes unity 3 Answers