0 votes

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?

in Engine by (684 points)
edited by

1 Answer

+2 votes
Best answer

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

or

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():
        #code

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

export(bool) var can_fire setget set_can_fire
by (1,106 points)
selected by

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!

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.

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.