Detect no keys pressed for x amount of time
This might seem like a relatively simple question, but I'm a complete idiot and I'm at my wits' end trying to do extremely basic code. I'm trying to make a character swap to an idle animation after x amount of time of being idle, but I can't even achieve a simple test print function with
void Update () {
if (Input.anyKeyDown == false) {
print("hello");
}
without it printing repeatedly due to it updating every frame. How do I make it detect my input (or lack thereof) over a period of time and only do something once?
Answer by Hellium · Dec 08, 2017 at 08:00 PM
public float inactivityThreshold = 5f ;
private float lastActivityTime ;
private bool inactive;
void Update ()
{
if (Input.anyKeyDown)
{
inactive = false ;
lastActivityTime = Time.time ;
}
if ( !inactive && Time.time - lastActivityTime > inactivityThreshold )
{
inactive = true ;
Debug.Log("Inactive") ;
}
}
This functioned exactly how I wanted, thank you. I can't even understand exactly why it works, sadly.
Alright it took me a while but I finally grasped the logic behind the code. I clearly don't have the brain for program$$anonymous$$g. Thank you for a swift response.
Your answer
Follow this Question
Related Questions
this is about idle 1 Answer
How can I fix my idle animations? 0 Answers
How can I effectively generate a random idle animation? Unity generates ugly transitions. 0 Answers
Character Won't Idle In Correct Direction 1 Answer
idle breathing motion 0 Answers