What is a possible way of having a cool-down timer for a weapon?
Please consider that all my work is in C#.
Thanks in advance!
What is a possible way of having a cool-down timer for a weapon?
Please consider that all my work is in C#.
Thanks in advance!
One easy way is to use a what I call a time stamp. Anytime you want a cool down you would do something like:
timeStamp = Time.time + coolDownPeriodInSeconds;
The in your firing code, you would only allow the gun to fire if the timeStamp <= Time.time;
if (timeStamp <= Time.time)
{
// Your firing code
}
In my opion, this is way better than timestamps.
Simple example using a proper coroutine.
public bool IsAvailable = true;
public float CooldownDuration = 1.0f;
void UseAbility()
{
// if not available to use (still cooling down) just exit
if (IsAvailable == false)
{
return;
}
// made it here then ability is available to use...
// UseAbilityCode goes here
// start the cooldown timer
StartCoroutine(StartCooldown());
}
public IEnumerator StartCooldown()
{
IsAvailable = false;
yield return new WaitForSeconds(CooldownDuration);
IsAvailable = true;
}
You can also use Coroutines in unity. They aren’t that hard to use and save you a lot of time in the future if you plan to have multiple cool downs going on.
Here’s an Example:
void Update()
{
StartCoroutine(TimerRoutine());
}
private IEnumerator TimerRoutine()
{
//code can be executed anywhere here before this next statement
yield return new WaitForSeconds(5); //code pauses for 5 seconds
//code resumes after the 5 seconds and exits if there is nothing else to run
}
I recommend looking into Coroutines because you can do a lot with them.