How do I store the float value from a variable that changes?

I’m working on a script for a fuel pump, where I want to hold spacebar to fill up a temporary fuel-variable, and when confirmed with return the tank will fill up.

   if (!fullTank && Input.GetKey(KeyCode.Space))
   {
       fuelPump = Mathf.Clamp(fuelPump + (Time.deltaTime * (rFuel * 0.05F)), 0.0f, emptyFuel);
       fuelCost = fuelPump * fuelPrice;
   }
   if (Input.GetKeyDown(KeyCode.Return))
   {
       currentFuel += fuelPump;
       fuelPump = 0;
       currentCash -= fuelCost;
       fuelCost = 0;
   }

fuelPump is the temporary holder, rFuel is the rate and emptyFuel is the amount of fuel needed.

This works fine, but when I press return the tank will fill up immediately, whereas I want currentFuel to fill up gradually just as the fuelPump does.

I tried using Mathf.Clamp in this fashion:

currentFuel = Mathf.Clamp(currentFuel + Time.deltaTime, currentFuel, currentFuel + fuelPump);

I want the “currentFuel + fuelPump” to be the max amount of fuel to fill, but since the currentFuel variable keeps changing, the tank will keep filling indefinitely.

Any ideas?

Well, you’ll have to fill the fueltank over several frames instead of instantly on a buttonpress…

maybe a coroutine, like

   //pass the total amount of fuel to pump into the routine
    IEnumerator FillTank(float fuelToPump){
     //while that amount is > 0, we update each frame
     while(fuelToPump > 0){
       //calculate how much fuel we want to pump this frame
       float pumpPerFrame = Time.deltaTime * pumpSpeed;
       //if that's more than how much we have remaining, set it to the remaining value
       if(fuelToPump < pumpPerFrame) pumPerFrame = fuelToPump;   
       //reduce remaining amount of fuel 
       fuelToPump -= pumpPerFrame;
       //add it to the current value
       currentFuel += pumpPerFrame;
       //wait for next frame before continuing this loop
       yield return null;
     }
    }

Then you can start this routine when you confirm with your return button.
I’ve never used coroutines like this… afaik it should work though. See also the documentation on coroutines.