0 votes

EDIT: Answered my own question.

Sorry for the poor title, but I'm not exactly sure how to word this. Essentially I'm trying to use variable variables, and I'm not sure what the syntax is in Godot (for reference, in PHP it's http://php.net/manual/en/language.variables.variable.php

func selectLevel(level):
   var LevelManager = get_node("/root/LevelManager")

   LevelManager.gotoScene(LevelManager.level)

I'm trying to get something to call the function selectLevel with the argument being which ever variable was selected, and have it choose the corresponding variable in LevelManager. So if the player clicks on a button that says "LevelOne", the button sends a signal to run select_level("LevelOne"), and then the LevelManager runs gotoScene with the argument being a different variable within LevelManager, named LevelOne.

Currently it just crashes because it's trying to find LevelManager.level, which doesn't exist, instead of swapping out the .level with .LevelOne.

If someone can show me what the correct method of using variable variables is in Godot, that'd be appreciated.

asked Feb 4, 2019 in Engine by denxi (403 points)
edited Feb 4, 2019 by denxi

1 Answer

0 votes
Best answer

Apparently variable variables aren't something that will be in GDscript at any point, but I've found a different way to do this. I have the initial button press pull the value of the variable I needed, then pass that value through to the function, rather than trying to have the function itself pull the value.

Button Press:

func _on_crow_pressed():
    var levelChoice = get_node("/root/LevelManager").crow
    select_level(levelChoice)

Select Level Function:

func select_level(level):
    var LevelManager = get_node("/root/LevelManager")

    LevelManager.goto_scene(level)

This works fine and is almost certainly more stable.

answered Feb 4, 2019 by denxi (403 points)
edited Feb 4, 2019 by denxi

I think get(), set() and call() should do what you're looking for. They don't have the syntax of variable variables as in PHP, but they should act in a similar way.

That said, I think these should be used as a last resort, so you should probably keep your solution.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.