x


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");
    }
}
more ▼

asked Mar 07 '11 at 01:37 AM

karl_ gravatar image

karl_
2.5k 41 53 70

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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));
more ▼

answered Mar 07 '11 at 02:08 AM

Statement gravatar image

Statement ♦♦
20.2k 35 71 176

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x62
x17

asked: Mar 07 '11 at 01:37 AM

Seen: 1533 times

Last Updated: Mar 07 '11 at 01:37 AM