Search code examples
godotgdscript

Append a number to a variable name in GDScript


I'd like to append an integer to the end of several variable names in GDSCript.

I'm working on a roguelike and I've decided to organise themed tilesets and NPC's and group them in folders by number (ie, theme 1 may be a crypt filled with undead, theme 2 a forest filled with animals). The idea is that at the start of level generation I can randomly select a number, generate a level and fill it with corresponding enemies.

For example (assuming the random number is 1)

tileset_to_use = tileset_1
NPC_mid_boss = folder_1/mid_boss
NPC_end_boss = folder_1/end_boss

Aside from a series of nested IF statements along the lines of:

if RNG = 1:
    tileset_to_use = tileset_1
    NPC_mid_boss = folder_1/mid_boss
    NPC_end_boss = folder_1/end_boss
elif RNG = 2:   
    tileset_to_use = tileset_2
    etc...

...what would be a more efficient way of doing this? Something like tileset+RNG I've looked into using dictionaries but, unless I've misunderstood them, they seem to be used for accessing values rather than generating variable names.


Solution

  • If all your themes share the same exact structure, you can do something similar to what Christopher Bennett proposes. Another option that may give you more flexibility, at the expense of possibly more repetition, is something like this:

    # Defined at class level
    const THEMES = [
        # Theme 1
        {
            tileset = 'tileset_1',
            NPC_mid_boss = 'folder_1/mid_boss',
            NPC_end_boss = 'folder_1/end_boss',
            # ...
        },
        # Theme 2
        {
            tileset = 'tileset_2',
            NPC_mid_boss = 'folder_2/mid_boss',
            NPC_end_boss = 'folder_2/end_boss',
            # ...
        },
        # ...
    ]
    
    
    func my_func():
        # Pick a random theme
        var theme = THEMES[randi() % THEMES.size()]
        tileset_to_use = theme.tileset
        # ...
    

    This also allows you to add more properties like arbitrary strings (e.g. theme name) or other things, and can be externalized to something like a JSON document if you want. But again, it requires more manual setup.