Best way to tell if node is loaded when exporting variables?

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

I have a exported variable with a setter/getter and a default value.

export var can_fire = true setget set_can_fire

This default value causes the setter to be triggered, which crashes because the nodes are not yet setup.

func set_can_fire(val):
	for muzzle in $MuzzleContainer.get_children():

I want to prevent this by checking if MuzzleContainer is loaded. What is the best way to determine if a node is loaded in GD Script? Obviously you could do if has_node("MuzzleContainer"): ... but is there a better way?

:bust_in_silhouette: Reply From: mateusak

Remove the setget and always use set_can_fire(val) to set it, providing the same result


export var _can_fire = true
var can_fire setget set_can_fire

func _init():
    can_fire = _can_fire

or, if you read long enough to see Zylann’s comment,

func set_can_fire(val):
    if is_inside_tree():

or, but I’m not sure this one works, don’t set a default value

export(bool) var can_fire setget set_can_fire

is_inside_tree is what I was looking for, where is Zylann’s comment? Not setting a default value worked, but I’d prefer to set it. Having a duplicate variable seems to violate SSOT and removing setget would break changes from the inspector. I appreciate all the different ways to get it done though!

jarlowrey | 2018-02-11 14:17

It doesn’t quite violate SSOT, since the first would be the initial value of can_fire, and not a copy of it. The _ prefix indicates that it’s a internal variable and shouldn’t be changed, so no confusion there. This is quite common if you wish to do object pooling, as a way to return to their default states without re-instancing.
It’s really just a preference between using RAM or CPU.
Anyways, glad to be helpful.

mateusak | 2018-02-11 20:38