Lerp between two int vaules smoothly

Hey Unity Pros,

so ive been trying to get this work since last night and it has given me hours of headache since because i dont know what is the problem or the bug in my code.

Basically I want to lerp from one int (eg.:1000points) to another (eg.:800points) using lerp to give that smoothing effect that it makes because its displayed to the player using UI Text.

The problem is that it doesnt work correctly or the way i want it to. It does weird things when I run the function such as showing me random numbers or just staying at 999points the whole time.

Here is an example of my code:

public void startSubtracting () {              //also.. this is running in Update

	score = 1000;
	score = (int)Mathf.Lerp (score, 800, subtractSpeed * Time.deltaTime);
	scoreText.text = score.ToString ();
}

I’d highly appreciate it if you guys could help me and thanks in advance!

So after struggling for a few more hours I managed to get the results I was looking for! (yaay:D) So I decided to post the little code that worked for me if someone else will need it in the future:) Thanks for the answeres tho!:slight_smile:

float lerp = 0f, duration = 2f;

	public void startSubtracting () {

		score = 1000;
		scoreTo = 800;
		lerp += Time.deltaTime / duration;
		score = (int)Mathf.Lerp (score, scoreTo, lerp);
		scoreText.text = score.ToString ();
	}

In my case the best solution for this is using vectors

using System.Collections; //for Vector3.Lerp
using UnityEngine.UI;

Vector3  score;
Vector3  target_score;
public Text score_text;

void Start () {
score= new Vector3 (0, 0, 0);
target_score= new Vector3 (100, 0, 0); // we run score to 100 points
}
void Update () {
score=Vector3.Lerp(score,target_score,Time.deltaTime);
score_text.text=(Mathf.RoundToInt(score.x)).ToString();
}

it’s simple and nicely and smooth

The third parameter in the Lerp method needs to be a float between 0 and 1.

int t=0; 
public void startSubtracting () {              //also.. this is running in Update
     score = 1000;
     score = (int)Mathf.Lerp (score, 800, t);
     t += subtractSpeed * Time.deltaTime;
     if(t>1)
          score=800;
     scoreText.text = score.ToString ();
 }

For more details see example here:
https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html

It’s a bit old thread, but it may help others looking for a solution.
I came up with the following formula:

        int IntLerp(int a, int b, float t)
        {
            if (t > 0.9999f)
            {
                return b;
            }

            return a + (int)(((float)b - (float)a) * t);
        }