How to access a variable of a instanced node?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lilithtb
:warning: 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)

:bust_in_silhouette: Reply From: stubbsy345

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

enemy.myVariable

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

var newVar = enemy.myVariable

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

lilithtb | 2017-09-16 21:00

i figured it out, just had to get_node()

lilithtb | 2017-09-17 02:50

:bust_in_silhouette: Reply From: VictorSeven

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

Then:

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

thanks this was helpful

lilithtb | 2017-09-17 02:50

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.

VictorSeven | 2017-09-17 10:42

Thank you so much man you’re awesome!

KurtBlissZ | 2019-06-20 06:37