Getting a variable by its name

Godot Version

4.3

Question

Is there any way to get a variable by its name? Here’s an example. It’s very generic but this is how it has to work:

level_1.gd

# Let's just say the scene is called "level_1", so var "name" = "level_1"
# LevelData is a global script
var data = LevelData.get_variable(name)

LevelData.gd

var level_1 = {
    "hp": 500,
    "time": 30,
    "target": 5
}

store the level_1 as a key of a dictionary with the value of dictionary of current level_1, if that make sense. instead of creating a variable for each levels
so the data level will look like this:

var data: Dictionary = { 
"level_1":{
    "hp": 500,
        "time": 30,
        "target": 5
    },
"level_2":{
    "hp": 400,
        "time": 50,
        "target": 10
    }
}
2 Likes

There is a get function! Takes a string, returns a value matching the variable name.

var data = LevelData.get(name)
var hp = data["hp"]
3 Likes

This is actually what I was looking for. Thanks a lot

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.