Answers for "unity c# get key down for x seconds"

C#
1

unity c# get key down for x seconds

// Timer controls
private float startTime = 0f;
private float timer = 0f;
public float holdTime = 2.0f; // how long you need to hold to trigger the effect
 
// Use if you only want to call the method once after holding for the required time
private bool held = false;
 
public string key = "g"; // Whichever key you're using to control the effects. Just hardcode it in if you want
   
void Update ()
{
    // Starts the timer from when the key is pressed
    if (Input.GetKeyDown(key))
    {
        startTime = Time.time;
        timer = startTime;
    }
 
    // Adds time onto the timer so long as the key is pressed
    if (Input.GetKey(key) && held == false)
    {
        timer += Time.deltaTime;
 
        // Once the timer float has added on the required holdTime, changes the bool (for a single trigger), and calls the function
        if (timer > (startTime + holdTime))
        {
            held = true;
            ButtonHeld();
        }
    }
 
    // For single effects. Remove if not needed
    if (Input.GetKeyUp(key))
    {
        held = false;
    }
}
 
// Method called after held for required time
void ButtonHeld()
{
    Debug.Log("held for " + holdTime + " seconds");
}
Posted by: Guest on September-24-2021

C# Answers by Framework

Browse Popular Code Answers by Language