- Home /
Check if key is pressed once
So what i want to do is if i pressed a key down once, a boolean should change to true/false. It seems i'm having problems with just this simple task. So GetKey updates always as the key is down, while GetKeyDown seems to react waaay to fast, activating and reactivating the bool about 5 times before i even get my finger off the key. Note that i'm doing this in the Update().
I guess one solution would be to put a quick counter after i GetKeyDown'd the key, but it just seems kind of cheap. Feels like i'm missing a perfect solution for this.
Any ideas? I'm apologize if this question have already been answered on other Questions or Unity Script References.
Answer by ExpiredIndexCard · Apr 17, 2013 at 11:56 PM
Bool example = true;
if (Input.GetKeyDown("the key")
example = !example;
Okay i guess i wasn't detailed enough, this is what i do:
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.C))
{
if ($$anonymous$$yBool == true)
{
$$anonymous$$yBool = false;
}
else
{
$$anonymous$$yBool = true;
}
}
This is done in Update() and it seems to update so fast it activates and reactives serveral times on one keypress.
Trying using the code i did. It's doing that because you change it to false, then unity sees that its false and then changes it to true. Let me explain my code. I used example = !example
. This means that it is changing the bool to the opposite of its current state. That way, unity only sees it change once. Tell me if that works
then unity sees that its false and then changes it to true : No, this is incorrect. SimonDiamonds logic is fine.
if (condition is met)
// do stuff
else // condition is not met
// do different stuff
@SimonDiamond try Get$$anonymous$$eyUp
I don't really see any difference between simondiamond's and expiredindexcard's logic.
simondiamonde code set $$anonymous$$yBool
to true
when it is true
and the other way around; while expiredindexcard's code flip the boolean value of $$anonymous$$yBool
, which also means that it will become true
when it is false
and the other way around.
Is there something that I have missed here?
There is no difference, my point was expiredindexcards statement was incorrect.
Your answer
Follow this Question
Related Questions
GetKey/GetKeyDown, Paired with Adjusting Stats 1 Answer
GetKey problem on client 0 Answers
GetKeyDown is fired more than once in Update() 1 Answer
Update() Function only fires once. 1 Answer
How to run a update function once 3 Answers