Skip to main content

Moving a player with the new Unity Input System

The new input system provides a number of advantages over the original input system.

The main one is that it can enable local multiplayer easily and that you can create events to handle button inputs that are run only when the button is pressed and not on every update.

You can also update the input actions from a single location and this will make the changes across all parts of the program that use this set of inputs.

First add the new input system and create default input actions.

Install the Input system package and create the default input actions for the player object.

https://www.youtube.com/watch?v=GyjGqOBsDrw&ab\_channel=LearnICTNow

Add code to your player object using the Input System of Unity.

Any movement of objects should be handled in the FixedUpdate method.

Note replace the Update method with FixedUpdate.

https://youtu.be/vFV0uJ0KE2Q

The code below is what is created in the video above.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
// Player variables
[SerializeField] private float _speed = 5.0f;
private Vector2 _movementInputVector;

private CharacterController _characterContoller;

// Start is called before the first frame update
void Start()
{
Debug.Log("Player created!");
_characterContoller = GetComponent<CharacterController>();
}

// Update is called once per frame
void FixedUpdate()
{
MovePlayer();
}

void MovePlayer() {
Vector3 move = new Vector3(_movementInputVector.x, 0.0f, _movementInputVector.y);

_characterContoller.SimpleMove(move * _speed);
}

void OnMove(InputValue iv) {
_movementInputVector = iv.Get<Vector2>();
}
}