- Home /
Input.GetKey(KeyCode.E) requires multiple presses.
Hello all,
I am trying to make a variable based script for my vehicular based game. As i'm making a simulator I need/would like a Engine variable for when the engine is either "on" or "off". To do this I have used:
public float engine;
and
void Start () {
engine = 0;
}
To control the variable. For the button input I am using:
if(Input.GetKey(KeyCode.E)){
if(engine == 0)
engine = 1;
else
engine = 0;
}
Yet this method only works the first time "E" is pressed then it requires two quick presses if not more. Is there a better solution which works all the time?
Many Thanks,
~James W
you need to use getkeydown, geykey will only work for the time you keep pressing.
Thanks for the fast reply @ozturkcompany your solution worked but tanoshimi wrote that as an answer which I could accept.
Answer by tanoshimi · Nov 24, 2013 at 01:10 PM
Assuming that you're using Input.GetKey inside Update(), your current code is flipping your engine on and off in every frame that the E key is pressed - possibly 60 times a second or more. Without realising, you're actually toggling the engine variable many times in every touch at the moment, and it's probably pretty arbitrary whether it ends on 0 or 1.
What you probably want is to use Input.GetKeyDown, which only returns true for the first frame in which a key is held.
Thanks for the detailed explanation as to why this was happening. Using Input.Get$$anonymous$$eyDown fixed the issue and it is now a toggle.