In this lesson, you will learn how to make your game objects responsive by capturing real-time keyboard commands using Unity’s Legacy Input Manager.
The Concept of Polling
In Unity, "polling" means checking the status of a specific button or axis every single frame. The Legacy Input Manager provides a central system that translates physical hardware presses (like pressing the 'W' key or moving a joystick) into abstract values your code can understand.
Instead of writing custom code to detect every specific keyboard key, we use the Input.GetAxis method. This method looks at the Input Manager (found in Edit > Project Settings > Input Manager), which maps physical keys to friendly names like "Horizontal" or "Vertical."
Implementing Movement
When you call Input.GetAxis, Unity returns a float value between -1 and 1. If you press 'A' or the Left Arrow, it returns -1; if you press 'D' or the Right Arrow, it returns 1. If no key is pressed, it returns 0.
Here is how you apply this to move an object in your scene:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
void Update()
{
// Get input from the "Horizontal" axis (A/D or Left/Right arrows)
float moveX = Input.GetAxis("Horizontal");
// Create a direction vector based on our coordinate space
Vector3 movement = new Vector3(moveX, 0f, 0f);
// Apply the movement to our transform position
transform.position += movement * moveSpeed * Time.deltaTime;
}
}
Why it Matters
By using Input.GetAxis instead of checking for specific keys like Input.GetKey(KeyCode.W), you allow your players to choose their own control schemes. Because the Input Manager handles the mapping, the same code will work for a keyboard, a mouse, or even a game controller without you needing to change a single line of script. This keeps your code clean and your gameplay flexible.
Key Takeaway: The Legacy Input Manager allows you to capture player intent via axis names, turning physical key presses into numerical values that you can multiply by your movement vectors to control objects in 3D space.