Search code examples
c#unity-game-enginelerp

Unity3D: Mathf Lerp too fast when timescale increases


I have an image with a fill amount component controlled by a Mathf Lerp. The problem is, the time for completion of the Mathf Lerp function decreases more than expected when the timescale increases.

When the timescale is equal to 2 the function should take half the time to complete but it takes less than that. Any idea why?

public static float demolishTime = 6.0f

public void OnClickDemolish()
{
    InvokeRepeating("demolishProgress", 0f, 0.1f);
}

void demolishProgress()
{        
    progress += (Time.deltaTime / demolishTime);
    demolishProgressBar[DemolishManager.demolishState].fillAmount = (float)Mathf.Lerp(0, 1, progress);
    if (progress >= 1) demolishCompleted();
}

Solution

  • Someone may correct me if I am wrong, but it may be due to the fact that the 3rd argument of InvokeRepeating, repeatRate, is not affected by timescale.

    You may consider using a Coroutine instead, like so:

    public static float demolishTime = 6.0f;
    
    public void OnClickDemolish() {
        StartCoroutine(demolishProgress());
    }
    
    IEnumerator demolishProgress() {
        float progressedTime = 0f;
    
        // Assuming 'demolishTime' is the time taken to entirely demolish the thing.
        while (progressedTime < demolishTime) {
            yield return new WaitForEndOfFrame();
            progressedTime += Time.deltaTime;
            demolishProgressBar[DemolishManager.demolishState].fillAmount = Mathf.Lerp(0, 1, progressedTime);
        }
    
        demolishCompleted();
    }