Course contentsShow
← Unity Game Development
Lesson 103 of 8282. Scripting and LifecycleFree lesson

Capturing Keyboard Input with Legacy Input Manager

Learners will implement basic character movement by polling the Input class to detect key presses during every frame update.

Capturing Keyboard Input with Legacy Input Manager

In this lesson, you will learn how to make your game interactive by polling the Input class to detect keyboard presses and move your objects in real-time.

Understanding Input Polling

In Unity’s Legacy Input Manager, "polling" means checking the status of a specific key during every single frame of your game. Since your Update() method runs once per frame, it is the perfect place to ask the engine, "Is the player holding this key down right now?"

If the answer is true, you can then apply changes to your object's Transform.position to move it across the screen.

Implementing Movement

To move an object, you check for a key press and then modify the transform.position. Here is a simple script to move an object to the right:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 5.0f;

    void Update()
    {
        // Check if the Right Arrow key is held down
        if (Input.GetKey(KeyCode.RightArrow))
        {
            // Move the object along the X-axis
            transform.position += Vector3.right * speed * Time.deltaTime;
        }
    }
}

Key Considerations

  1. Input.GetKey: This returns true as long as the key is held down, which is ideal for continuous movement.
  2. Time.deltaTime: Always multiply your movement speed by Time.deltaTime. This ensures that your object moves at a consistent speed regardless of how fast or slow the user’s frame rate is.
  3. The Input Class: This is a global class, meaning you can access it from any script without needing a GetComponent call or a direct reference. It acts as a bridge between the physical keyboard and your game logic.

By placing these checks inside Update, you allow the game to respond instantly to the user's intent, creating the foundation for character control.

Key Takeaway: Use the Input.GetKey method inside the Update lifecycle method to continuously poll for player input and apply real-time transformations to your GameObjects.