Cheaper way to check input

Hi folks,

I’m doing a 2D game where the player can move left or right.
I want to be able to check easily if the player is moving or not.

To do that I’m checking the keyboard inputs.

The first way I thought of was to check at Update() and to store the result in a boolean :

bool isMoving;

void Update() {
    isMoving = Input.GetKey(Keycode.LeftArrow) || Input.GetKey(Keycode.RightArrow);
}

void Check() {
	if (isMoving)
		// do something
}

But I don’t need to check each frame, I need it on a per-demand basis.

So I wondered if it would be better (and cheaper in memory usage) to implement that kind of boolean method :

bool IsMoving() {
	bool b = Input.GetKey(Keycode.LeftArrow) || Input.GetKey(Keycode.RightArrow);
	return b;
}

void Check() {
	if (IsMoving())
		// do something
}

The answer may seem obvious but I wonder if there would be issues with the second method, or significant performance difference ?

I have to precise that I also check the inputs individually (to move the player, obviously).

Thanx in advance for any advice. Have a nice day.

This second script still needs to check for input on every frame so isn’t going to make any difference to performance. If you’re really interested in comparing them you can check performance of scripts by using the profiler.

You can make a logic gate if say, you don’t want to detect input in certain states (while the game is paused for example), i.e:

private void Update(){
     if(_isPaused){
          return;
     }

     if(GetButtonDown //etc etc..
}

but generally during gameplay it needs to be checked every frame

It should be faster in theory but I don’t think you’ll notice a difference. Checking input is fast enough to do it each frame. If you have problems with performance, it’s probably something else.