- Home /
Method for checking if a key is pressed without slowing game.
I have had my scripts as
void update()
{
if(input.key...){do bla bla}
}
for every key but I felt it was greatly slowing down the game having all of these ifs for keyup and key down. Is there a more efficient way such as a method that's called when a key is pressed.
I'll explain what's going on here. The reason why it's "Slowing" your frames is because every frame it's checking to see if you have pressed a key. I can imagine if it's slowing your game then you have a bunch of if statements. The best way to handle this is with a simple manager / case statment. First check if a key was pressed then send it off to a method as an argument.
Answer by Xarbrough · Sep 21, 2015 at 12:45 AM
It's very unlikely that if statements are slowing down your game. You could check for Input.GetKey hundreds of times per frame and wouldn't notice it much unless something else is going on. You should use the Profiler, fps counters or the C# Stopwatch class to measure performance if you feel you're getting stuttering. But the if statement itself is one of the cheapest operations. There might be something else involved like expensive calculations when comparing etc., but that's why we have the Profiler.
Answer by drex150 · Sep 21, 2015 at 02:23 AM
You can just use the following:
if (Input.anyKey)
{
//do whatever here.
}
If you mean you want to detect any keyup event, then yes, there is a way: OnGUI and the Event class.
void OnGUI()
{
Event e = Event.current;
if (e.type == EventType.$$anonymous$$eyUp)
{
Debug.Log("User released key: " + e.keyCode)
// e.keyCode contains the key code of the released key
}
}
Hmm, I don't think so. The only way you could really check if any individual key is up or down is to check that key specifically. So you'd have to check for every key possible if it's up or down.
A way to prevent it from checking every single frame if every single key is pressed would be to put all the keys inside that Input.any$$anonymous$$ey if statement like so:
if (Input.any$$anonymous$$ey)
{
if (Input.Get$$anonymous$$ey("i"))
{
print("i worked!");
}
if (Input.Get$$anonymous$$ey("j"))
{
print("j worked!");
}
}
Now it will only check what key was pressed when any key is actually pressed. This would only help slightly though because any time a key is pressed and held down, it's going to check all the other keys every frame again until you are pressing no keys.
What exactly are you trying to have happen in your game? That could help possibly.
It's a 2d side scroller and the input.getkey down make a bool true which will invokerepeating method that controls movement and on key up makes it false and cancels the method.