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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

There must be a neat way to express this

Discussion in 'Scripting' started by unity_2e_7kz8DqNKDjA, May 11, 2018.

  1. unity_2e_7kz8DqNKDjA

    unity_2e_7kz8DqNKDjA

    Joined:
    Jan 31, 2018
    Posts:
    9
    I often find myself writing (coroutine) code that does something like this:

    Code (CSharp):
    1. if (value < target) {
    2.     value += speed * Time.deltaTime;
    3.     someParameter.value = value;
    4.     if (value >= target)
    5.         yield break;
    6.     else
    7.         yield return null;
    8. }
    9. else if (value > target) {
    10.     value -= speed * Time.deltaTime;
    11.     someParameter.value = value;
    12.     if (value <= target)
    13.         yield break;
    14.     else
    15.         yield return null;
    16. }
    I _hate_ that "if" statement, but it seems necessary because I need to know whether I'm doing =< or >=. I'm sure there must be a more compact way of expressing this?
     
  2. TJHeuvel-net

    TJHeuvel-net

    Joined:
    Jul 31, 2012
    Posts:
    818
    You want to lerp something towards a target with a speed? Why dont you just do Mathf.MoveTowards in your coroutine, until your value is approx. equal to target?
     
  3. UziMonkey

    UziMonkey

    Joined:
    Nov 7, 2012
    Posts:
    206
    Try something like this.

    Code (CSharp):
    1. float dist = target - value;
    2. float delta = speed * Mathf.Sign(dist) * Time.deltaTime;
    3. value += delta;
    4.  
    5. if(Mathf.Abs(delta) > Mathf.Abs(dist))
    6.   yield return null;
    7. else
    8.   yield break;
     
    unity_2e_7kz8DqNKDjA likes this.
  4. unity_2e_7kz8DqNKDjA

    unity_2e_7kz8DqNKDjA

    Joined:
    Jan 31, 2018
    Posts:
    9
    Hey didn't know about that function! That's *exactly* what I was looking for :)