0 votes

In my main scene I have created an instance of another scene. How can I get the value of a variable that was created within the script of the newly instanced object?

I have:

var scn_enemy = preload("res://scenes/enemy.tscn")

func ready():
var enemy = scn

in Engine by (27 points)

2 Answers

+1 vote

It's fairly straightforward. Your instance is now stored to the variable 'enemy', so all you have to do is:


if you want to store it in a new var simply:

var newVar = enemy.myVariable
by (290 points)

What if the variable was in the script that is a child of the root node and not in the root node?

i figured it out, just had to get_node()

+2 votes

Stubbbsy345's is correct, but I usually prefer to use getters and setters. When it is a simple variable, maybe it looks a bit stupid, but sometimes you want a more complex behaviour when you set or get a variable.
Also, it allows the use of duck typing, which is one of the best features of GDScript.

In the variable you want to instance:

var my_var = 5

func setVar(value):
    my_var = value

func getVar()
    return my_var


instanced_variable.setVar(6) #Then, inside instanced_variable, my_var = 6
var my_var_from_instace = instanced_variable.getVar()
by (73 points)

thanks this was helpful

Regarding your question of "What about if the var is in a script located on a child node?" then this method can simplify your life a bit. You have:

func setVar(value):
    get_node("child").my_var = value

func getVar()
    return get_node("child").my_var

And then you can retrieve the information as I indicated before:

var my_var_from_instace = instanced_variable.getVar()

This is useful because if you change something in your scene, for example, the child node is renamed from "child" to "my_node", or you change its parent or something like that, changing the getVar and setVar methods will do the trick. If you don't do this, you would have to look in every script where you instance the node and change it.

Thank you so much man you're awesome!

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.