I'm creating a simple game and I'm using SDL2 for handling inputs from controllers. The issue is that SDL is not giving me the correct index for the controller which causes my game to crash.
/receive the controller index given by SDL
int cIdx = evt.cdevice.which;
switch (evt.type)
{
case SDL_CONTROLLERAXISMOTION:
{
//.........
break;
}
case SDL_CONTROLLERBUTTONUP:
{
InputButton sender = InputButton(evt.cbutton.button);
controllerStates[cIdx]->SetButtonState(sender, false);
break;
}
case SDL_CONTROLLERBUTTONDOWN:
{
if (evt.cbutton.button != SDL_CONTROLLER_BUTTON_INVALID)
{
InputButton sender = InputButton(evt.cbutton.button);
controllerStates[cIdx]->SetButtonState(sender, true);
}
break;
}
case SDL_CONTROLLERDEVICEADDED:
{
if (SDL_IsGameController(cIdx))
{
SDL_GameController * controller = SDL_GameControllerOpen(cIdx);
AddController(controller);
}
break;
}
case SDL_CONTROLLERDEVICEREMOVED:
{
RemoveController(controllers[(cIdx)]);
break;
}
}
This works just fine when the user add the controller for the first time, SDL is sending me 0 as index in the SDL_CONTROLLERDEVICEADDED event and also 0 for the other events. The problem is that if the user tries disconnect and reconnect the controller SDL send 0 as index in SDL_CONTROLLERDEVICEADDED event and 1 for the other events which causes the game to crash.
I can also make simple check if the index to avoid the crash but it will be useless since all controller events will be ignored.
Any help will be appreciated.
Thanks