Unity Input System: Movement
Objective: Setup simple movement using Unity’s new input system.
Create a 3D Object > Cube named Player, and tag it Player. From Unity’s menu, open window > package manager and search for input. Install the Input System as shown below.
Now within the project window, right click to create > input actions to create PlayerInputActions within the input folder. Select this input action then check the Generate C# Class and select apply, see below. This will generate the PlayerInputAction C# script automatically.
Double click the PlayerInputActions, highlighted above, and add a new action, Walk. Set the Walk action type to value and control type to vector2. Now selecting the + on Walk, add up\down\left\right composite and assign the WASD keys from the keyboard as shown. Add another action named Run and bind the left shift key.
The Run properties are shown below and use an interaction to toggle run mode, if the left shift key is held down for 1 second. Uncheck default for hold time so that the desired time can be entered. Select the save asset button for PlayerInputActions.
Create a new C# script named PlayerInput and place it in Input folder. This C# script will require the UnityEngine.InputSystem namespace, and four variables. The PlayerInputActions are stored in the _input variable. A Vector2 _inputMove will be used to store player input for movement. A bool _running is used to toggle run mode as is the float _speed, which uses a property to return either 3f if _running is true, otherwise returns 1f.
In void Start(), assign _input to the PlayerInputAction script created earlier then enable it. Next assign the methods to each action as shown below. For each Walk or Run action, performed checks if the key is pressed for the required time, and canceled checks for its release. Simply put this script tells the _input system that it is listening, and assigns a method to be performed if the action event, Walk or Run, happens.
These methods are shown below. Each receives a CallbackContent obj from the InputSystem. For Walk_performed, _inputMove is assigned from the WASD key value in obj, allowing diagonal movement, and Walk_canceled sets _inputMove to zero for both x & y coordinates. The Run toggles _running to true for Run_performed and false for Run_canceled.
If _inputMove is not (0, 0) then Movement() method is called within void Update() .
The actual Player movement is handled by the Movement() method. This method converts the vector2 _inputMove into the Vector3 direction then translates the Player in that direction, as shown below.
This article describes implementing a simple movement system for Unity’s new input system. The new Unity input system is literally a series of actions with a fancy user interface that must be assigned. The advantage of the new system is that this uses Unity’s event system which broadcasts events to any object which is listening.