0
0
Unityframework~7 mins

Controller/gamepad support in Unity

Choose your learning style9 modes available
Introduction

Using a controller or gamepad lets players enjoy your game with a physical device. It makes gameplay easier and more fun for many people.

You want players to use a gamepad instead of keyboard and mouse.
Your game needs to detect button presses or joystick movements.
You want to support popular controllers like Xbox or PlayStation pads.
You want to read input from multiple controllers at once.
You want to create custom controls for different game actions.
Syntax
Unity
using UnityEngine;

void Update() {
    if (Input.GetButtonDown("Jump")) {
        // code to make the player jump
    }
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");
    // use moveHorizontal and moveVertical to move player
}

Input.GetButtonDown checks if a button was just pressed this frame.

Input.GetAxis reads joystick or arrow key movement as a float between -1 and 1.

Examples
This checks if the main fire button on the controller was pressed.
Unity
if (Input.GetButtonDown("Fire1")) {
    Debug.Log("Fire button pressed");
}
This moves the player based on joystick or arrow keys input.
Unity
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0, vertical);
transform.Translate(movement * speed * Time.deltaTime);
This lists all connected controllers by name.
Unity
string[] names = Input.GetJoystickNames();
foreach (string name in names) {
    Debug.Log("Controller connected: " + name);
}
Sample Program

This script moves a game object using the controller's joystick or arrow keys. It also logs a message when the jump button is pressed.

Unity
using UnityEngine;

public class SimpleController : MonoBehaviour {
    public float speed = 5f;

    void Update() {
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(moveX, 0, moveZ);
        transform.Translate(move * speed * Time.deltaTime);

        if (Input.GetButtonDown("Jump")) {
            Debug.Log("Jump button pressed!");
        }
    }
}
OutputSuccess
Important Notes

Make sure your Input settings in Unity have the correct button and axis names.

Test your game with different controllers to ensure compatibility.

Use Input.GetJoystickNames() to detect connected controllers at runtime.

Summary

Controller support lets players use gamepads for input.

Use Input.GetButtonDown and Input.GetAxis to read buttons and joysticks.

Check connected controllers with Input.GetJoystickNames.