I used this to detect when a Gamepad/joystick is activated/plugged in.
Also, the controller/joystick does not need to be plugged in before you start your game. You can turn it on/off during gameplay. I tested this many times.
private void FixedUpdate()
{
if (Input.GetJoystickNames().Length > 0) // Auto switch if gamepad is activated.
{
if (Input.GetJoystickNames()[0].Length > 0)
{
if (!IsInDirectMode)
{
IsInDirectMode = true; // toggle mode
CurrentClickTarget = transform.position; // clear the click target
}
}
else
{
if (IsInDirectMode)
{
IsInDirectMode = false;
CurrentClickTarget = transform.position;
}
}
}
if (IsInDirectMode)
{
ProcessDirectMovement();
}
else
{
ProcessMouseMovement();
}
}