Topic was automatically imported from the old Question2Answer platform.
Asked By
lilithtb
Old Version
Published before Godot 3 was released.
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_enemy.instance()
add_child(enemy)
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
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.