Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to use easing inside coroutine to change a float value?

Discussion in 'Scripting' started by Abdo023, May 1, 2021.

  1. Abdo023

    Abdo023

    Joined:
    Dec 18, 2017
    Posts:
    64
    I would like to increase the value of a float over time but with added In-Out easing.
    Here I'm using 'Mathf.Lerp' and I know there is 'Mathf.Smoothstep' but in SmoothStep, I can't seem to control the speed of the easing itself. I would like the easing to start from a certain value to another value over a specific time(range?) I choose. For example, if the float is changing from 0 to 100, I would like the easing to be from 0 to 20 and again from 70 to 100.

    Here is the current code I'm using:
    Code (CSharp):
    1.  
    2. float minValue = 0;
    3. float maxValue = 100;
    4. float duration = 10;
    5. float value;
    6.  
    7. void Start()
    8.      {
    9.            StartCoroutine(IncreaseSpeed(minValue, maxValue, duration));
    10.      }
    11.   private IEnumerator IncreaseSpeed(float start, float end, float duration)
    12.      {
    13.          float time = 0;
    14.          while (time <= duration)
    15.          {
    16.              time = time + Time.deltaTime;
    17.              value = Mathf.Lerp(start, end, time / duration);
    18.              yield return null;
    19.          }
    20.      }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,760
    Tons of ways... you could use a function (look up easing functions) or else make a custom AnimationCurve object to define how to ease the alpha through the lerp.

    Or easiest (no pun intended) way is probably to grab DOTWeen or LeanTween or iTween off the asset store and look how they do easing. It's gonna be a super-generic solution which would apply in your case, since all you need to do is control the alpha (time) term.
     
  3. Abdo023

    Abdo023

    Joined:
    Dec 18, 2017
    Posts:
    64
    Thanks for the reply.

    I already tried using an Animation Curve but it still doesn't give me manual control over the values. All I can do is manipulate it in the inspector.
    I do have DoTween but never used it. Can it add easing to a float? will I be able to control the value or is it a generic EaseInOut thing?