+1 vote

I will show an example.

func _ready():
    var variable = 123

output: Null
If the variable is global, then everything works.

var variable = 123
func _ready():

output: 123

How to access a local variable using the get function?

in Engine by (111 points)

1 Answer

0 votes
Best answer

A local variable only exists on the stack, when the function gets executed. Its lifetime is limited to the block in which it is declared, it's not part of the object itself and it won't persist outside of the function.
get only works for variables that are part of the object, those you declare outside of functions.

If you want to get the content of a local variable, you can only do it from within the function it was declared in, like this:

func _ready():
    var variable = 123

But if you want the variable to stay in memory after the function is executed, it should be a member variable declared outside of the function, and it will be accessible by writing something like this:

# From within another script
var other = get_node("Path/To/Your/First/Node")


by (27,962 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 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 webmaster@godotengine.org with your username.