I'm trying to implement cooldown for actions in my game - prevent same action from happening for some time. I.e. the character should jump only once in 3 seconds even if user presses "jump" button more often than that.
For some reason the jumpCooldown
just gets stuck at like 2 and won't move on thus making my cooldown infinite.
In particular why jumpCooldown
does not get to 0 and how to fix this code? I'm also open to other better approaches for implementing cooldown?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExperminetMovement : MonoBehaviour
{
static bool canJump = true;
public float jumpCooldown = 3f;
void Start() { }
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
canJump = CoolDownFunction();
}
}
public bool CoolDownFunction()
{
jumpCooldown -= Time.deltaTime;
if (jumpCooldown <= 0)
{
jumpCooldown = 3f;
return true;
}
return false;
}
}