How to use Unity’s new Input System to simplify and expand your game’s controls

This guide will show you how to stop using if-else statements for player controls with Unity’s new modern approach

Image for post
Image for post
Create games with awesome control schemes quickly and easily! Photo by Glenn Carstens-Peters on Unsplash
if(Input.GetKeyDown(Keycode.A)){
// move left
}else if(Input.GetKeyDown(Keycode.D)){
// move right
}else if(Input.GetKeyDown(Keycode.W)){
// move up
}else if(Input.GetKeyDown(Keycode.S)){
// move down
}

Installation

Image for post
Image for post
Install the Input System from the Unity Package Manager window.
Image for post
Image for post
Be sure to generate a new C# class when you create a new InputAction Asset.

Set up your Actions and Triggers

Image for post
Image for post
The Action Maps, Actions, and Properties views help visualize inputs based on their purpose in your game.

Writing Player Controls

PlayerControls controls;void OnEnable() {
controls.Gameplay.Enable();
}
void OnDisable() {
controls.Gameplay.Disable();
}
void Awake(){
controls = new PlayerControls();
controls.Gameplay.MeleeAttack.performed += Melee;
}
void Melee(InputAction.CallbackContext ctx){
// Code for performing a melee attack
}
Vector2 vel;void Awake(){
controls = new PlayerControls();
controls.Gameplay.Move.performed += ctx => {
vel = ctx.ReadValue<Vector2>();
};
controls.Gameplay.Move.canceled += ctx => {
vel = Vector2.zero;
};
}
void Movement(){
// code using "vel" as player's velocity
}
void Update(){
Movement();
}

Alternate method — On the Update Loop

void FixedUpdate(){
var keyboard = Keyboard.current;
if(keyboard == null){ return; }
if(keyboard.zKey.wasPressedThisFrame){
// perform action here
}
}

Conclusion

Freelance game designer / developer. Full stack developer. Board game geek and cat tamer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store