- Home /
Usage timer/weapon cooldown...
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!
Answer by robertbu · Feb 25, 2013 at 07:15 PM
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
if (timeStamp <= Time.time)
{
// Your firing code
}
Amazing, dude! Thanks! I like your Time Stamp theory, might consider referring it to my friends too. You are awesome!
@robertbu what do timeStamp and cooldown perdiods in second stand for?
'timeStamp' is a float declared at the class level. In Javascript it would be:
private var timeStamp : float;
...in c# it would be:
private float timeStamp;
'coolDownPeriodInSeconds' is the number of seconds for the cooldown. You can replace it with a constant like 2.5, or you can declare it as a variable, and assign it a value.
WHERE DO WE PLACE THE$$anonymous$$ ON THE SCRIPT?
Initialize the variables at the top of the script, then when you want to start the timer, do timeStamp = Time.time + coolDownPeriodInSeconds;
. When you're getting the input from the player, only do the ability if(Time.time <= timeStamp)
Answer by tbriz · Jan 09 at 08:23 PM
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;
}
Answer by Mizacoto · Jul 28, 2020 at 07:25 AM
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.
Hey. it doesn't work, it starts the corountine every second.
@akaBl4ck check my answer below, proper way to use coroutine cooldown.
Your answer
Follow this Question
Related Questions
PLease Help 1 Answer
A node in a childnode? 1 Answer
Timer help please 1 Answer
How may I get the children (direct and dependents) of a game object? 2 Answers
Error in my Fps input controller 0 Answers