Detect Gamepad


I am making a function that detect the gamepad on the start of a game. The thing is that it just works after some time and I don't know why.

I put the function below on an initial room on an object that initializes a bunch of things on the Create Event. It doensn't work.

Then I put that on a Room End Event. Don't work.

Then I put the same function on a button event, clicked it and it works. Does anyone knows why...? o_Ô

/// @description gamepad_detect( )
var gp_num = gamepad_get_device_count();
var port = -1;
for (var i = 0; i < gp_num; i++;){
    if( gamepad_is_connected(i) ){
        port = i;

if( port != -1 ){
    gamepad_set_axis_deadzone(port, 0.15);
    gamepad_set_button_threshold(port, 0.5);

global.connected_gamepad = port;

alert("*************************************** GAMEPAD ON PORT " + string(port) )
return port;
This is the evidence image. The function is called on the Create Event on the initializer object. After that it goes to a Menu Room and I click a button with the same function as above and now the GamePad is in the port 4.


As @devKathy kindly points out to me in a conversation, I should use The Asynchronous Events under System > Gamepads.

I put the code below in an Async Event on a persistent object et voilà works like a charm.

Thanks a lot @devKathy, you are the best. =]

if( ds_exists(async_load, ds_type_map) ){
    var wEventType = ds_map_find_value(async_load, "event_type");
    if(wEventType == "gamepad discovered"){
        var wPadIndex = ds_map_find_value(async_load, "pad_index");
        alert("Gamepad discovered", wPadIndex);
        if( wPadIndex != -1 ){
            gamepad_set_axis_deadzone(wPadIndex, 0.15);
            gamepad_set_button_threshold(wPadIndex, 0.5);

        global.connected_gamepad = wPadIndex;
    }else if(wEventType == "gamepad lost"){
        var wPadIndex = ds_map_find_value(async_load, "pad_index");
        alert("Gamepad lost", wPadIndex);

        global.connected_gamepad = -1;