GMS 2 Execute script with variable

Discussion in 'Programming' started by Mael, Oct 11, 2019.

  1. Mael

    Mael Member

    Joined:
    Feb 12, 2019
    Posts:
    6
    Hello everyone!
    I have a small problem in my mobile project. I created a button that should lead to the next level. All the level atributes are saved in scripts: scr_level1 , scr_level2 , scr_level 3 and so on. So in the button I added these lines:

    // this button is in rm_game
    //when button is pressed/released
    nextLevel = global.actualLevel + 1; // this global variable is set when the level script is executed
    script = "scr_level"+string(nextLevel);
    script_execute(script);
    room_goto(rm_game);

    With this I would expect this for example: I open level 1. scr_level1 loads all the settings. global.actualLevel = 1 now.
    When the button appears and you click it, nextLevel = 1 + 1. Then script = "scr_level"+"2". script_execute(scr_level2); room_goto(rm_game);

    But instead I get this crash message:

    ############################################################################################
    FATAL ERROR in
    action number 1
    of Mouse Event for Left Released
    for object obj_nextLevel:
    (null) argument 1 incorrect type (string) expecting a Number (YYGI32)
    at gml_Object_obj_nextLevel_Mouse_7 (line 4) - script_execute(script);
    ############################################################################################
    --------------------------------------------------------------------------------------------
    stack frame is
    gml_Object_obj_nextLevel_Mouse_7 (line 4)

    How can I resolve the problem? I dont want to create different buttons for each level.
    Thank you for your time. :)
     
  2. TheouAegis

    TheouAegis Member

    Joined:
    Jul 3, 2016
    Posts:
    6,889
    script_execute takes script IDs, not names. So you'd need to use asset_get_index() to find the ID.
     
    Mael likes this.
  3. Yal

    Yal GMC Memer GMC Elder

    Joined:
    Jun 20, 2016
    Posts:
    3,703
    use script = asset_get_index("scr_level"+"2") instead of script = "scr_level"+"2"

    The string "scr_level2" is different from the ID scr_level2, which is a number like 27 by the time you're running the game.
     
    Mael likes this.
  4. Mael

    Mael Member

    Joined:
    Feb 12, 2019
    Posts:
    6
    Thank you very much, it worked! I would never had gotten it correct. Have a nice day :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice