How can I detect if a gamepad is present?

I need to detect if currently connected. From there, I will remove the second player if it isn’t.

3 Answers

3

On PC, you can use Input.GetJoystickNames(), which returns an array of strings of the names of the joysticks that are connected. If that array is empty, there are no pnp joysticks connected, I guess.

I hope that helps!

I’m currently trying to figure out how to tell if there is a Bluetooth joystick connected on an Android device, but that information doesn’t seem to be quite as handily available.

I'd guess that if your gamepad isn't showing up in Input.GetJoystickNames(), it is registering itself as a bluetooth keyboard to try to get better compatibility with older versions of Android. For whatever that's worth 2 years later...

–

rbisso, did you ever find a solution to your issue: "I'm currently trying to figure out how to tell if there is a Bluetooth joystick connected on an Android device"? I am seeking an answer to the same question.

–

FYI, on PC I’m finding some GamePads (MOGA for example) stay registered as connected in Windows 10 — even months later. And generate an Axis value if -1,-1.

Not sure if that helps anyone else. But I’ll probably create an exception where until a joysticks value changes for the first time it continues to consider them disabled.

you can do this in C#

private int Xbox_One_Controller = 0;
    private int PS4_Controller = 0;
void Update()
{
string[] names = Input.GetJoystickNames();
        for (int x = 0; x < names.Length; x++)
        {
            print(names[x].Length);
            if (names[x].Length == 19)
            {
                print("PS4 CONTROLLER IS CONNECTED");
                PS4_Controller = 1;
                Xbox_One_Controller = 0;
            }
            if (names[x].Length == 33)
            {
                print("XBOX ONE CONTROLLER IS CONNECTED");
                //set a controller bool to true
                PS4_Controller = 0;
                Xbox_One_Controller = 1;

            }
        }


if(Xbox_One_Controller == 1)
{
//do something
}
else if(PS4_Controller == 1)
{
//do something
}
else
{
// there is no controllers
}
}

Amazing soluction! But if i have two PS4 controllers conected in same time, or two Xbox One controllers? how could it differentiate?

–

Whats the names[x].Length == A Keyboard?

–