I keep getting caught up on this, I’m using Time.deltaTime as a countdown for a cooldown. Yet when I add it to an if statement it seems to only take one frame into account. If I add the line to the update function alone, it works fine, but need a way to detect when I’ve pressed a button.
#pragma strict
var topLid : GameObject;
var bottomLid : GameObject;
var regenSanity : float = 15.0;
private var canClick : boolean = true;
var timer : float = 3.0;
private var sanityScript : InsanityManager;
function Start()
{
sanityScript = GameObject.Find("First Person Controller").GetComponent(InsanityManager);
topLid = GameObject.Find("EyeLid_Top");
bottomLid = GameObject.Find("EyeLid_Bottom");
}
function Update()
{
if(Input.GetMouseButtonDown(0) && canClick == true)
{
timer -= Time.deltaTime;
topLid.animation.Play("BlinkTop");
bottomLid.animation.Play("BlinkBottom");
sanityScript.currentSanity -= regenSanity;
canClick = false;
}
if(timer <= 0)
{
timer = 3.0;
canClick = true;
}
}
your timer -= Time.deltaTime; seems to have been in the wrong spot. It’s only going to decrement on frames where the mouse is being clicked. Here’s what I propose to make it simpler.
I would say instead of having the canClick variable, make that implicit by making that state true when timer is less than or equal to zero and get rid of canClick. Then always decrement from timer. Only when you want to set the cooldown active, set the timer variable to the amount to wait.
GetMouseButtonDown() only returns true on the single frame that a mouse button is clicked. It won’t return true again until the user releases and reclicks the button.
If you want every frame the button is pressed, you can use GetMouseButton().
If you’re trying to implement a cooldown, you could use a coroutine like @Key_Less suggested, or you could separate out your logic, something like this:
//two modes: processing cooldown, or waiting for button press
if (canClick) {
//wait for button press
if (Input.GetMouseButtonDown(0)) {
//set up cooldown
timer = 3.0;
canClick = false;
//handle button
topLid.animation.Play("BlinkTop");
bottomLid.animation.Play("BlinkBottom");
sanityScript.currentSanity -= regenSanity;
}
} else {
//process cooldown
timer -= Time.deltaTime;
if (timer <= 0) {
canClick = true;
}
}