how to use Lerp outside the update funciton?

Hey guys i just wanto ask a quick question on how can i use Lerp outside the update function. I used a for loop but that didn’t work out. In my case I can’t use it in update function but there still must be a way to do it right?

Here’s the code:

    void Start ()
    {
        rend = GetComponent<Renderer>();
        rend.material.shader = Shader.Find ("FresnelPack/Transparent Rim Unlit");
        //rend.material.SetFloat ("_Scale", 0.0f);
        for (int i = 0; i < 40; i++) {
            rend.material.SetFloat ("_Scale", Mathf.Lerp (0.8f, 0f, Time.deltaTime * 10));
        }
    }

First a very quick explanation: Update() gets called once every frame, whereas most other functions, like Start, usually get called once and complete in a single frame. So if you just put a for loop like this, it will basically stall your game, do the entire loop in a single frame, and then continue. You can’t actually see anything animate with a Lerp if it all happens in a single frame, it will just appear to jump immediately to the end. That’s why it’s usually used in Update, so that you can show it across several frames, so the player can actually see it.

That said, the easiest way to make it work in your case is to turn Start into a Coroutine, which will make it work across several frames, but you might want to look up how Coroutines work at some point if you end up needing to add code for something else to the Start method:

    System.IEnumerator Start (
    {
        rend = GetComponent<Renderer>();
        rend.material.shader = Shader.Find ("FresnelPack/Transparent Rim Unlit");
       //rend.material.SetFloat ("_Scale", 0.0f);
       for (int i = 0; i < 40; i++) {
            rend.material.SetFloat ("_Scale", Mathf.Lerp (0.8f, 0f, Time.deltaTime * 10));
            yield return new WaitForEndOfFrame();
       }
    }
1 Like

Thank you verymuch I will see how it goes!

Your code did work (tested that with debug.log) but the Lerp still gets called only once even now in update function.

It’s weird because it was working earlier today in the Update function. Than i just went to the Cinema … wached mission impossible 5 … came back home and the code is broken.

Ok thats off topic so any idea what might cause that?

1 Like

Mission Impossible 5 is well known for causing previously working code to break.

You’ll need to post the actual code that isn’t working for this conversation to go anywhere.

1 Like