Node in Class Member Variable?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By kaleidx

I’m trying to make my code cleaner and easier to modify.
Currently I’m doing something like this:

get_parent().get_node("Timer").wait_time = 1

But I’m finding I have to edit that number several times. I also might edit node sometimes. So instead of writing get_parent().get_node() every time I tried to set it to a variable …

var timer = get_parent().get_node("Timer")

So I can do:

timer.wait_time = 1

I get no instance error if I put it in class member section. I can put it in functions without error but I may need it several times. Is there a different way so I just need to write it once?

In summary, I can’t do this:

extends x
var timer = get_parent().get_node("Timer")
_func x(x)
    timer.wait_time = 1

But this works:

extends x

_func x(x)
    var timer = get_parent().get_node("Timer")
    timer.wait_time = 1

It’s not exactly necessary right now as the script is small but would like to learn if there is a better way when projects get bigger.

:bust_in_silhouette: Reply From: endragor

This makes the property assigned during _ready() callback, i.e. when the node is added to the scene tree:

onready var timer = get_parent().get_node("Timer")

It is similar to doing:

var timer
func _ready():
  timer = get_parent().get_node("Timer")

Notice that, when using this approach, you should make sure the variable is not accessed before the node is added to the scene tree (but that’s unlikely to be the case, since you are using get_parent()).

Also, you should think about reorganizing your tree - normally a node shouldn’t manage its sibling nodes, like in your example. Consider making the timer a child of the node in question instead.

:bust_in_silhouette: Reply From: hilfazer

Use onready keyword in your variable’s definition

onready var timer = get_parent().get_node("Timer")

It will initialize your variable at the very beginning of _ready() function call, when your node is already in SceneTree and has a parent.