askvity

How to Detect Controller Connected Unity

Published in Unity Controller Detection 4 mins read

The primary way to detect a controller connected in Unity is by using Input.GetJoystickNames().

Detecting Controllers in Unity

According to Unity's capabilities, a developer's sole way of detecting a controller is using Input.GetJoystickNames(). This method returns an array of strings, where each string is the name of a detected joystick (controller). If a controller is connected, its name will appear in this array.

Understanding Input.GetJoystickNames()

  • Input.GetJoystickNames() returns a string[].
  • Each element in the array corresponds to a connected joystick.
  • The string value is typically the name of the controller (e.g., "Wireless Controller", "Xbox 360 Controller").
  • An empty array is returned if no joysticks are connected.

The Challenge: No Connection Notifications

A crucial point to understand is that an application does not get a notification that a controller has connected or disconnected. This means Unity doesn't provide built-in events like OnControllerConnected or OnControllerDisconnected.

How to Detect Changes (Connections/Disconnections)

Since there are no direct events, detecting when a controller is connected or disconnected requires a proactive approach. The common method is to periodically check the result of Input.GetJoystickNames().

  1. Store the current state: Keep track of the list of connected joystick names you found during the last check.
  2. Periodically check: In a script (e.g., in an Update or a coroutine), call Input.GetJoystickNames() regularly.
  3. Compare states: Compare the newly obtained list of names with the stored list.
    • If a name appears in the new list that wasn't in the old list, a controller has likely connected.
    • If a name disappears from the new list that was in the old list, a controller has likely disconnected.
  4. Update stored state: Replace the old list with the new list for the next check.

Practical Implementation Outline

Here's a simplified idea of how you might implement this periodic check in a Unity script:

using UnityEngine;
using System.Linq; // Needed for Linq methods

public class ControllerDetector : MonoBehaviour
{
    private string[] connectedControllers;
    private float checkInterval = 1.0f; // Check every 1 second
    private float timer;

    void Start()
    {
        // Initialize with currently connected controllers
        connectedControllers = Input.GetJoystickNames();
        Debug.Log("Initial controllers: " + string.Join(", ", connectedControllers));
        timer = checkInterval;
    }

    void Update()
    {
        timer -= Time.deltaTime;
        if (timer <= 0)
        {
            CheckForControllerChanges();
            timer = checkInterval;
        }
    }

    void CheckForControllerChanges()
    {
        string[] currentControllers = Input.GetJoystickNames();

        // Check for newly connected controllers
        var newlyConnected = currentControllers.Except(connectedControllers).ToArray();
        if (newlyConnected.Length > 0)
        {
            Debug.Log("Controller(s) connected: " + string.Join(", ", newlyConnected));
            // Trigger connection logic here
        }

        // Check for disconnected controllers
        var disconnected = connectedControllers.Except(currentControllers).ToArray();
        if (disconnected.Length > 0)
        {
            Debug.Log("Controller(s) disconnected: " + string.Join(", ", disconnected));
            // Trigger disconnection logic here
        }

        // Update the stored list for the next check
        connectedControllers = currentControllers;
    }
}
  • This script uses LINQ (Except()) to find differences between the arrays. You could also do this with loops.
  • The checkInterval determines how often you check. A smaller interval detects changes faster but might be slightly less performant (though checking joystick names is generally very fast).

Summary

Method Description Detection Type Notified By Unity?
Input.GetJoystickNames() Returns an array of strings representing currently connected joystick names. State check No
Periodic Check Implementing logic to repeatedly call Input.GetJoystickNames() and compare results. Change over time N/A (Developer Implemented)

In essence, while Unity provides the tool (Input.GetJoystickNames()) to see what is connected now, detecting the event of a connection or disconnection requires you to monitor this state yourself over time.

Related Articles