0 votes

Is it possible to dinamycally create variables by using array elements or dictionary keys as variable names?

For instance:

var demo = ["var1","var2"]

func _ready():
    set(demo[0], "Hi")
    print(get(demo[0]))

I'm expecting to see "Hi" in the console, but I get a Null

Godot version 3.2.3
in Engine by (30 points)
edited by

1 Answer

+2 votes
Best answer

No, it doesn't work this way. Variables made with var or accessed with get and set have to be declared somewhere first:

var demo = ["var1","var2"]

# Declaring
var var1
var var2

var demo = ["var1","var2"]

func _ready():
    set(demo[0], "Hi")
    print(get(demo[0]))

If you want dynamic vars created at runtime, you can use a dictionary:

var demo = ["var1","var2"]
var vars = {}

func _ready():
    vars[demo[0]] = "Hi"
    print(vars[demo[0]])

If you are reaaaaally desperate to use get and set for some reason, you can override _get and _set:

var demo = ["var1","var2"]
var vars = {}

func _ready():
    set(demo[0]) = "Hi"
    print(get(demo[0]))

func _get(key):
    return vars[key]

func _set(key, value):
    vars[key] = value
by (29,042 points)
selected by
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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.