Unity new Input system - Learn and Use in your game

Complete guide to implement unity new input system in your game 

Are you tired of wrestling with Unity's old input system, trying to create smooth character movement? 🤔 You're not alone. Many developers struggle with outdated input methods, leading to clunky controls and frustrated players. But what if there was a better way?

Enter Unity's New Input System – a game-changer for creating fluid, responsive character movement. This powerful tool promises to revolutionize how you handle player input, but it can seem daunting at first. Don't worry, we've got you covered! In this ultimate guide, we'll walk you through everything you need to know about Unity New Input System, from basic setup to advanced techniques.

You'll discover how to implement buttery-smooth character movement, optimize performance, and even customize the system to fit your unique game needs. Whether you're a beginner looking to level up your skills or a seasoned pro seeking to streamline your workflow, this guide will equip you with the knowledge to master Unity's New Input System. Ready to transform your game's movement mechanics? Let's dive in and explore the seven key areas that will take your character control to the next level!

unity input system tutorial

Let's understand unity new input system

Key features and improvements

The Unity New Input System brings a host of powerful features and improvements to game development. Here are some key highlights:

  • Action-based input: Allows you to define abstract actions like "Jump" or "Move" instead of directly polling for specific keys or buttons.

  • Device-agnostic input: Easily support multiple input devices without changing your core logic.

  • Input rebinding: Enables players to customize controls without code changes.

  • Enhanced control schemes: Create different control schemes for various play styles or platforms.


Feature Old Input System New Input System
Cross-platform support Limited Extensive
Input remapping Manual implementation Built-in support
Action-based input Not available Core feature
Performance Good Optimized

Advantages over the old input system

The New Input System offers several advantages that make it a superior choice for modern game development:

  1. Improved cross-platform compatibility: Easily adapt your game to different platforms and input devices.

  2. Enhanced code organization: Separates input logic from game logic, leading to cleaner, more maintainable code.

  3. Better support for complex input scenarios: Handles simultaneous inputs and complex button combinations more effectively.

  4. Integrated with Unity's visual scripting: Allows for rapid prototyping and easier implementation for non-programmers.

Compatibility with different platforms

You'll find the New Input System incredibly versatile when it comes to platform compatibility. It supports a wide range of platforms and input devices, including:

  • PC (keyboard, mouse, gamepads)

  • Mobile devices (touch controls, accelerometer)

  • VR and AR headsets

  • Game consoles (PlayStation, Xbox, Nintendo Switch)

This broad compatibility ensures that your game can reach a wider audience without the need for extensive platform-specific code. The system's device-agnostic approach allows you to focus on creating engaging gameplay mechanics rather than worrying about input implementation details for each platform.

Setting up new unity input system

unity input system tutorial


Installing and enabling the package

To get started with Unity's New Input System, you'll need to install and enable the package. Here's how you can do it:

  1. Open your Unity project

  2. Go to Window > Package Manager

  3. Search for "Input System"

  4. Click "Install" to add the package to your project

Once installed, Unity will prompt you to restart the editor. After restarting, you'll need to enable the new system:

  1. Go to Edit > Project Settings > Player

  2. Find the "Active Input Handling" option

  3. Change it to "Both" or "Input System Package (New)"

Option

Description

Both

Allows using both old and new input systems

Input System Package (New)

Uses only the new input system

Creating an Input Action Asset

Now that you've enabled the new Input System, it's time to create an Input Action Asset:

  1. Right-click in your Project window

  2. Select Create > Input Actions

  3. Name your asset (e.g., "PlayerControls")

This asset will store all your input configurations for easy management and reuse across your project.

Configuring input actions for movement

With your Input Action Asset created, you can now set up actions for character movement:

  1. Double-click the Input Action Asset to open the Input Action editor

  2. Click the "+" button to add a new action map (e.g., "Player")

  3. Within the action map, add actions for movement:

    • "Move" (Vector 2)

    • "Jump" (Button)

Binding keys and controls

The final step is to bind keys and controls to your actions:

  1. Select the "Move" action

  2. In the Binding section, click "+" to add bindings

  3. Choose "2D Vector Composite" for WASD/Arrow key movement

  4. Bind W/Up Arrow to "Up", S/Down Arrow to "Down", A/Left Arrow to "Left", and D/Right Arrow to "Right"

  5. For "Jump", add a binding and select the spacebar

Now that you've set up the New Input System, you're ready to implement character movement in your Game.

Implements basic character movement in your game

unity input system

Creating a player controller script

To implement basic character movement in Unity's new Input System, you'll start by creating a player controller script. This script will serve as the central hub for managing your character's movement.

  1. In your Unity project, right-click in the Project window

  2. Select Create > C# Script

  3. Name it "PlayerController"

Open the script and add the following namespace at the top:

using UnityEngine;
using UnityEngine.InputSystem;

Next, create variables for movement speed and the character's Rigidbody component:

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
}

Reading input values

With the new Input System, you'll use the InputAction class to read input values. Add the following to your script:

private InputAction moveAction;

void Awake()
{
    moveAction = new InputAction("Move", binding: "<Gamepad>/leftStick");
    moveAction.AddCompositeBinding("2DVector")
        .With("Up", "<Keyboard>/w")
        .With("Down", "<Keyboard>/s")
        .With("Left", "<Keyboard>/a")
        .With("Right", "<Keyboard>/d");
    moveAction.Enable();
}

Translating input to character movement

Now that you're reading input values, it's time to translate them into actual character movement. Add this method to your script:

void FixedUpdate()
{
    Vector2 input = moveAction.ReadValue<Vector2>();
    Vector3 move = new Vector3(input.x, 0, input.y);
    rb.MovePosition(rb.position + move * moveSpeed * Time.fixedDeltaTime);
}

Handling different movement types

To handle different movement types like walking, running, and sprinting, you can use a simple state machine. Here's an example:

Movement Type

Speed Multiplier

Input Condition

Walk

1x

Default

Run

1.5x

Left Shift held

Sprint

2x

Left Ctrl held

Implement this in your script:

private float speedMultiplier = 1f;

void Update()
{
    if (Keyboard.current.leftShiftKey.isPressed)
        speedMultiplier = 1.5f;
    else if (Keyboard.current.leftCtrlKey.isPressed)
        speedMultiplier = 2f;
    else
        speedMultiplier = 1f;
}

Modify your FixedUpdate method to use the speed multiplier:

void FixedUpdate()
{
    Vector2 input = moveAction.ReadValue<Vector2>();
    Vector3 move = new Vector3(input.x, 0, input.y);
    rb.MovePosition(rb.position + move * moveSpeed * speedMultiplier * Time.fixedDeltaTime);
}

With these implementations, you've created a solid foundation for basic character movement using Unity's new Input System. Next, we'll explore advanced movement techniques to further enhance your character's mobility and responsiveness.

Advanced Movement Techniques

 

new unity input system

Implementing smooth acceleration and deceleration

To create more realistic character movement, you'll want to implement smooth acceleration and deceleration. This technique adds a natural feel to your character's motion, making the game more immersive.

 

Here's how you can achieve this effect:

  1. Use Vector3.SmoothDamp() for gradual speed changes

  2. Implement a coroutine for acceleration over time

  3. Apply drag to simulate deceleration

Parameter

Description

Typical Value

Current velocity

Current speed of the character

Vector3

Target velocity

Desired speed

Vector3

Ref velocity

Reference velocity for smooth transitions

Vector3

Smooth time

Time to reach target velocity

0.1f - 0.5f

Adding jump and gravity

Jumping is a crucial element in many games. To implement a realistic jump mechanic:

  1. Apply an initial upward force when the jump button is pressed

  2. Simulate gravity by constantly applying downward force

  3. Use raycasts to detect ground contact

Here's a simple implementation:

void Jump()
{
    if (IsGrounded() && Input.GetButtonDown("Jump"))
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }
    
    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);
}

Incorporating character rotation

Smooth character rotation enhances the overall movement experience. You can achieve this by:

  1. Using Quaternion.Slerp() for gradual rotation

  2. Aligning the character with the movement direction

  3. Implementing a look-at function for targeting

Handling different terrains and slopes

Adapting your character's movement to various terrains and slopes adds depth to your game. Consider these techniques:

  • Use raycasts to detect surface normals

  • Adjust movement speed based on terrain type

  • Implement slope limits to prevent unrealistic climbing

By mastering these advanced movement techniques, you'll create a more dynamic and engaging character controller. Next, we'll explore how to optimize these movement mechanics for better performance.

Optimizing Movement & Performance

unity inputsystem


Using Time.deltaTime for frame-rate independence

When optimizing movement performance in Unity new Input System, one crucial aspect is ensuring frame-rate independence. This is where Time.deltaTime comes into play. By incorporating this value into your movement calculations, you can create smooth and consistent motion across different devices and frame rates.

Here's how you can implement Time.deltaTime in your movement code:

void Update()
{
    Vector2 movement = inputActions.Player.Move.ReadValue<Vector2>();
    transform.Translate(movement * moveSpeed * Time.deltaTime);
}

Using Time.deltaTime multiplies your movement by the time elapsed since the last frame, ensuring consistent speed regardless of frame rate.

Implementing input buffering

Input buffering is a technique that can significantly improve the responsiveness of your game. It allows you to store inputs for a short period, executing them even if they're received slightly before or after the ideal frame.

Here's a simple example of how you might implement input buffering:

Buffer Component

Description

Input Queue

Stores recent inputs

Buffer Time

Duration to hold inputs

Process Method

Executes buffered inputs

private Queue<InputAction.CallbackContext> inputBuffer = new Queue<InputAction.CallbackContext>();
private const float bufferTime = 0.1f; // 100ms buffer

void Update()
{
    ProcessBuffer();
}

void OnJump(InputAction.CallbackContext context)
{
    inputBuffer.Enqueue(context);
}

void ProcessBuffer()
{
    while (inputBuffer.Count > 0 && Time.time - inputBuffer.Peek().time <= bufferTime)
    {
        var input = inputBuffer.Dequeue();
        // Process the buffered input
    }
}

Reducing input lag

To minimize input lag, you can employ several strategies:

  1. Use Input.GetKeyDown() instead of Input.GetKey() for more responsive inputs

  2. Implement prediction algorithms for network-based games

  3. Optimize your game's overall performance to reduce frame time

Remember, the goal is to create a responsive and smooth player experience. By combining these techniques, you'll significantly enhance the performance of your movement system using Unity's new Input System.

Customizing and Extending the Input System

 

unity inputsystem

Creating custom input actions

When working with Unity's New Input System, creating custom input actions allows you to tailor your game's controls to your specific needs. Here's how you can create and implement custom input actions:

  1. Open the Input Action Asset

  2. Add a new action map

  3. Create a new action within the map

  4. Define the action's properties

  5. Bind the action to specific controls

Step

Description

1

Open Input Action Asset in Project window

2

Click "+" to add new action map

3

Right-click in action map to add new action

4

Set action name, type, and control type

5

Drag controls from binding section to action

By following these steps, you can create unique input actions that perfectly suit your game's mechanics and feel.

Implementing context-sensitive controls

Context-sensitive controls allow your game to respond differently to the same input based on the current game state. This adds depth and flexibility to your control scheme. To implement context-sensitive controls:

  1. Create multiple action maps for different contexts

  2. Use C# scripts to switch between action maps

  3. Utilize action callbacks to execute context-specific code

For example, you might have separate action maps for "Combat" and "Exploration" modes. When the player enters combat, you switch to the Combat action map, changing how certain inputs behave.

Supporting multiple control schemes

To make your game accessible to a wider audience, it's crucial to support multiple control schemes. Here's how you can implement support for keyboard, gamepad, and touch controls:

  1. Create separate control schemes in your Input Action Asset

  2. Define bindings for each control scheme

  3. Use device-specific UI elements for different input methods

Control Scheme

Advantages

Keyboard

Precise, familiar for PC gamers

Gamepad

Comfortable for console-style play

Touch

Intuitive for mobile devices

By supporting multiple control schemes, you ensure that players can enjoy your game regardless of their preferred input method. Remember to test each control scheme thoroughly to provide a smooth experience across all platforms.

 

Now that you've customized and extended the Input System, let's move on to debugging and troubleshooting common issues you might encounter.

Debugging and Troubleshooting

 Also Read:

Using the Input Debugger

The Input Debugger is your best friend when it comes to troubleshooting issues with Unity's new Input System. This powerful tool allows you to visualize and analyze input events in real-time, making it easier to identify and resolve problems.

 

To access the Input Debugger:

  1. Go to Window > Analysis > Input Debugger

  2. Select the devices you want to monitor

  3. Start your game and observe the input events

The Input Debugger provides valuable information such as:

  • Active input devices

  • Button states

  • Axis values

  • Touch inputs

Feature

Description

Event Trace

Shows a chronological list of input events

Device State

Displays the current state of all connected devices

Action Map

Visualizes the mapping between inputs and actions

Common movement-related issues and solutions

When implementing character movement with the new Input System, you might encounter some common issues. Here are a few problems and their solutions:

  1. Unresponsive movement:

    • Ensure your Input Action Asset is properly set up

    • Check if the Player Input component is correctly configured

  2. Jittery or inconsistent movement:

    • Use Time.deltaTime to smooth out frame-rate dependent movement

    • Implement interpolation or extrapolation for networked games

  3. Input lag:

    • Reduce the number of intermediate layers between input and movement

    • Consider using Input System's lower-level APIs for direct input polling

Performance profiling for input-heavy games

For games with complex input requirements, performance optimization is crucial. Use Unity's Profiler to identify and address input-related bottlenecks:

  1. Open the Profiler (Window > Analysis > Profiler)

  2. Focus on the CPU Usage and Input System categories

  3. Look for spikes or consistent high usage in input-related methods

To optimize input performance:

  • Use Input System's event-driven model instead of polling

  • Implement input buffering for combos or complex input sequences

  • Consider using Unity's Job System for parallel input processing in large-scale games

By mastering these debugging and optimization techniques, you'll be well-equipped to create smooth, responsive movement systems using Unity's new Input System. Next, we'll explore some advanced topics and best practices to further enhance your game's input handling.

Conclusion:

Unity's New Input System revolutionizes how you handle character movement in your games. By mastering this powerful tool, you've unlocked a world of possibilities for creating smooth, responsive, and customizable player controls.

Remember, the key to success lies in practice and experimentation. Start with the basics, implement advanced techniques, and don't forget to optimize your movement code for peak performance. As you continue to explore the Input System's capabilities, you'll discover new ways to enhance your game's interactivity and player experience. Keep pushing the boundaries of what's possible, and watch your Unity projects come to life with fluid, intuitive movement that will captivate your players.


Frequently Asked Questions (FAQs) about Unity's New Input System

1. What is Unity’s New Input System?

Unity’s New Input System is an advanced way to handle user inputs across multiple devices, including keyboards, gamepads, touchscreens, and VR controllers. It replaces the legacy Input Manager with a more flexible and modular approach, allowing developers to create custom input mappings and handle complex interactions efficiently.

2. How do I enable the New Input System in Unity?

To enable the New Input System in Unity:

  • Open Edit > Project Settings > Player.
  • Scroll to Active Input Handling and select Both or Input System Package (New).
  • Install the Input System package from the Unity Package Manager if it’s not already added.

3. How do I create custom input actions?

To create custom input actions:

  • Go to Assets > Create > Input Actions to generate an Input Actions asset.
  • Open the asset and define action maps, actions, and bindings for various inputs.
  • Assign the actions to scripts using the PlayerInput component or Input System API.

4. Can I use both the old and new Input Systems together?

Yes, Unity allows using both systems simultaneously by setting Active Input Handling to Both in the Player settings. However, this approach is mainly for transitioning and may cause conflicts in some cases. It’s recommended to fully migrate to the New Input System for better performance and maintainability.

5. How do I read input in a script using the New Input System?

You can use the PlayerInput component or manually reference an InputAction in your script:

csharp
public class PlayerController : MonoBehaviour { public InputAction moveAction; private void OnEnable() { moveAction.Enable(); } private void OnDisable() { moveAction.Disable(); } void Update() { Vector2 movement = moveAction.ReadValue<Vector2>(); transform.Translate(movement * Time.deltaTime); } }

This approach allows for greater flexibility in handling input across different control schemes.

Would you like me to add more details on any of these topics?