Can someone please show me how to add a 1 second cool down to this script. Please use java script. Thank you in advance.
Hi Smackerio,
Welcome to Unity Answers!
In the future it would be better for people helping you if you actually paste your code into some code tags like I am doing below.
Check out this short tutorial about how to ask great questions, to have a higher chance of receiving great answers : Answers Tutorial
This code should get you going in the right direction. The basic logic is you want to set a variable to hold the value of when your player will be able to fire again, and then set a variable for how long you want the delay to be. Then in your Update loop you can set the NextFire variable to Time.time + FireRate and make sure that the current time is greater than your NextFire time before you allow the player to shoot.
#pragma strict
//The interval you want your player to be able to fire.
var FireRate : float = 1.0;
//The actual time the player will be able to fire.
private var NextFire : float;
function Update () {
//If the player is pressing fire AND The current time is > than when I want them to fire
if(Input.GetButton("Fire1") && Time.time > NextFire)
{
//If the player fired, reset the NextFire time to a new point in the future.
NextFire = Time.time + FireRate;
//Weapon firing logic goes here.
Debug.Log("Firing once every 1s");
}
}
I would create two new variables into a Weapon class:
float cooldownCounter = 1;
bool coolingdown = false;
This way each weapon could have its own cooldown time.
And then
if (!weapon.coolingdown) {
Fire();
weapon.coolingdown = true;
}
else {
weapon.coolingdownCounter -= Time.deltaTime;
if (weapon.coolingdownCounter <= 0) {
weapon.coolingdown = false;
}
In other words, if the weapon is not coolingdown, then you can fire. After you fire, it will need to cooldown.
If the weapon is not cooling down, then decrease the amount of time that has passed. When it reaches zero, then the weapon is available to fire again.
This code is in C#, but it should be quick to make it into unityscript.
You can either check for when your NextFire is, or you can check when your LastFire was.
Logic: Time.time >= NextFire or LastFire + Interval <= Time.time