- Home /
Question by
alexkaskasoli · Feb 16, 2014 at 04:45 AM ·
c#buttoncrouchhold
If button held 3 seconds do something
I'm trying to do a Crouch/Lay down system:
1) Press C => crouch
2) Hold C for 3 seconds => lay down
The logical way to do this seemed to be to use a timer:
if (Input.GetButtonDown ("Crouch")) {
print("Crouch");
if (crouching)
Stand();
else
Crouch();
// Start Timer
timer = new Timer(crouchDelay);
timer.Elapsed += new ElapsedEventHandler(CrouchTimer);
timer.Enabled = true;
}
else if (Input.GetButtonUp ("Crouch")) {
timer.Enabled = false;
}
But this isn't working, getting timers to work in unity has proven to be a real pain the £$%. In this case the method CrouchTimer() is always called instantly, no matter what value crouchDelay has.
If you wanted to call a method ONLY if a key was held for 3 seconds, how would you do it?
Comment
Best Answer
Answer by AlucardJay · Feb 16, 2014 at 05:07 AM
It's just a matter of logic :
public var timeToCrouch : float = 3.0;
var crouchTimer : float = 0;
var isCrouching : boolean = false;
var isProne : boolean = false;
function Update()
{
if ( Input.GetKeyDown(KeyCode.C) )
{
if ( isCrouching || isProne )
{
Stand();
}
else
{
Crouch();
}
}
else if ( Input.GetKey(KeyCode.C) )
{
crouchTimer += Time.deltaTime;
if ( isCrouching && crouchTimer > timeToCrouch )
{
Prone();
}
}
else if ( Input.GetKeyUp(KeyCode.C) )
{
}
}
function Stand()
{
isCrouching = false;
isProne = false;
}
function Crouch()
{
crouchTimer = 0;
isCrouching = true;
isProne = false;
}
function Prone()
{
isCrouching = false;
isProne = true;
}