How to increase an int (or float) smoothly over time? (Mathf.Lerp?)

Hi, I’ve got a question involving increasing a value smoothly over time.

I have a spaceship that fires its thrusters while holding down the mouse key. I would like a speed value displayed that smoothly increases as the mouse key is pressed, and smoothly decreases when released. I am adding code to an existing script. I’m pretty sure I’m using Mathf.Lerp incorrectly. Would anyone be able to help? Thank you.

void Update () {

	int speed = 0;

	// Start all thrusters when pressing Fire 1
	if (Input.GetButtonDown("Fire1")) {		
		foreach (SU_Thruster _thruster in thrusters) {
			_thruster.StartThruster();

			speed += (int) Mathf.Lerp (0, 1000, Time.deltaTime);
			speedText.text = speed.ToString ();
		}
	}
	// Stop all thrusters when releasing Fire 1
	if (Input.GetButtonUp("Fire1")) {		
		foreach (SU_Thruster _thruster in thrusters) {
			_thruster.StopThruster();

			speed -= (int) Mathf.Lerp (0, 1000, Time.deltaTime);
			speedText.text = speed.ToString ();
		}
	}
}

You’re probably not using Mathf.Lerp correctly.
If 0 < c < 1, Mathf.Lerp(a,b,c) returns a*(1-c)+b*c.
If c > 1, the lerp returns b. If c < 0, the lerp returns a.

Your actual problem is that the code you have will only be executed when you press down the key and when you let go of the key. It won’t run when you’re holding down the key. What you want instead is Input.GetKey.

So something that you could do is (pseudocode):

void Update() {
  if (Input.GetKey(SOMEKEY)) {
    speed += 10 * Time.deltaTime; // Cap at some max value too
  }
  else {
    speed -= 10 * Time.deltaTime; // Cap at some min value too
  }
}

(There’s no need to use lerp.)

Ok I wrote this for future readers, this is my own solution to this problem if you need a cap
with this your float variable will go from 0 to 1 and you will be able to decide “how fast” (you just need to change 5 with any number):

movementFB2 = movementFB2 < 1f ? movementFB2 + Mathf.Lerp(0, 1, Time.deltaTime * 5) : 1f;

(this is assuming you are using Input.GetKey in an Update, also you will need to put a 0f movementFB2 if you are not using that input).

I get errors when trying this. Namely saying I cannot convert “float” into “int”. I am trying this script with a player health replenish. Rather than having to pick up a health power up I want the player to gradually heal himself. My health scripts for health.currentHealth are all in “int”. I mean several scripts would have to be changed on several enemies that inflict damage. So how can I slowly increase an “int” over time?