Detecting joystick disconnect
I see this question has been asked before, but I can't find a solution to it.
So I have a local multiplayer setup with two xb-one gamepads and that's functioning as expected. I'm keeping track of Input.GetJoystickNames().Length. If I disconnect a joystick during gameplay or even in editor, the .Length keeps it's value at 2.
I have my code setup so that if the value=1, make the 2nd player use the keyboard+mouse.
Now I have to restart the game/editor to set Input.GetJoystickNames().Length to match connected joysticks number.
Is there any method to detect a joystick disconnection??
Answer by petersvp · Aug 26, 2016 at 09:20 PM
Implement your own InputManager using Win32's RawInput API in C++. This way you can detect disconnections and handle them yourself. You can even differentiate between multiple mice this way.
Here is sample implementation but for mice. Alter is to suit your needs. It properly detects XBOX Gamepads.
C++ DLL: http://pastebin.com/0Szi8ga6 C# script: http://pastebin.com/4h3CqpYy
Note that in Editor, Unity steals RawInput devices very feequently. I did not had any issues in a build, however.
Answer by robpuk38 · Nov 28, 2016 at 02:06 PM
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
}
}
This answer could be expanded to include any controller, save that information in a list and compare the size for when Input.GetJoystickNames() changes its Length. When that happens, you'd just need to compare the new list to the saved one to figure out which controller is not on the list anymore.