How do I...in script, detect if a controller is plugged in Runtime.

As the title says, im trying to find a way to detect when player 2 plugs in the second controller, in script.
As i would like to start functions and UI effects when player 2 gets involved into the game.
I know about this page: How do I…? | Input System | 1.0.2
but i dont know how to implement it into a script, or where the script should be or why.

I need a helping snippet example like most of the examples in the unity documents to fully understand how it works.
Thanx

I reformatted Unity’s code snippet into a more complete example:

public class Example : MonoBehaviour
{
    void Awake()
    {
        InputSystem.onDeviceChange += OnDeviceChange;
    }

    void OnDestroy()
    {
        InputSystem.onDeviceChange -= OnDeviceChange;
    }

    public void OnDeviceChange(InputDevice device, InputDeviceChange change)
    {
        switch (change)
        {
            case InputDeviceChange.Added:
                // New Device.
                break;
            case InputDeviceChange.Disconnected:
                // Device got unplugged.
                break;
            case InputDeviceChange.Reconnected:
                // Plugged back in.
                break;
            case InputDeviceChange.Removed:
                // Remove from Input System entirely; by default, Devices stay in the system once discovered.
                break;
            default:
                // See InputDeviceChange reference for other event types.
                break;
        }
    }
}

The new snippet showcases the entire ‘listening’ process without causing a memory leak. (See C# Actions for more info on that).

In OnDeviceChange() you can put your own code.
In your case, you are probably looking to display UI elements for whenever Player 2 is Added or Reconnected.

As for this:

This particular script can be attached to any GameObject.
Whenever an InputDevice undergoes a change, OnDeviceChange() will be performed no matter which GameObject this component is attached to.

Unity’s InputSystem.onDeviceChange is an Action. When you do += or -= to an Action, you are adding or removing a subscriber.
Whenever Unity invokes the InputSystem.onDeviceChange Action, all subscribers (I.E. your code) will be executed.

1 Like

Amazing! thank you. you probably helped more people than me right now.
Thanx yet again.

1 Like

I’m glad I could be of assistance! :smile:
Happy coding!

1 Like

Thank you so much

1 Like