Increment a value every second when key is being pressed.

I’m making a platformer game and trying to add an option that, depending on how long you press a key, the jump will be a certain height. So it would be something like

private int timer = 3;
public float JumpForcePS;
private float PowerJump = 0;

void Update()
 {
  if (Input.GetKey(KeyCode.LeftShift) && IsGrounded)
        {
            if (timer > 0)
            {
                PowerJump += JumpForcePS;
                timer--;
              //Somehow make it wait a second before executing again.
            }
        }
        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            rb.velocity = Vector2.up * PowerJump;
            timer = 3;
            PowerJump = 0;
        }
 }

In my case I made JumpForcePS (PerSecond) 7. If I leave the code as is it will always reach 21. I want it so that if you press for 1 second the PowerJump will equal 7, if you press for 2 seconds it will equal 14 and if you press it for 3 seconds it will be 21. How can I make it so the code in the “If (timer > 0)” statement executes once every second. Have in my that I have more code in the Update function. I just copied this one because it’s the one I need help with.

I think it would be a lot easier to just count how long the key was pressed for, and then work out what that means for your power at the end, rather than trying to increment every second.

In the code below I just time how long the button was pressed for.
Then when the key is finally released we take the value of how long they pressed for, and turn that into a speed to apply by a little rounding and multiplying.

public float JumpForcePS;

private int maxMultiplier = 3;
private float jumpTimer = 0;
private bool jumping = false;

void Update()
{
    if (Input.GetKeyDown(KeyCode.LeftShift) && IsGrounded){
        jumpTimer = 0;
        jumping = true;
    }


    if (Input.GetKey(KeyCode.LeftShift) && jumping)
    {
        jumpTimer += Time.deltaTime;
    }

    if (Input.GetKeyUp(KeyCode.LeftShift) && jumping) {
        // currently jumpTimer is any floating point number, but we want to convert that to 7, 14 or 21
        // first, FloorToInt will mean we have possible values 0, 1, 2, 3
        // adding 1 will give possible values 1, 2, 3, 4
        // taking the minimum value of that and 3 will give 1, 2, 3
        // multiple that by your force to get distinct values 7, 14, 21 (when JumpForcePS = 7)
        int jumpPower = JumpForcePS * Mathf.Min(Mathf.FloorToInt(jumpTimer)+1, maxMultiplier);
        
        jumping = false;
        rb.velocity = Vector2.up * PowerJump;
    }
}

You might wanna try using Time.deltaTime.

Here’ s a reference: Unity - Scripting API: Time.deltaTime

The Update method runs once per frame. The Time.deltaTime contains the time that passed since the last frame.