Check if script of a node has variable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By tiernich
:warning: Old Version Published before Godot 3 was released.

My question is simple, but cant find the answer, i wanna simple check if a node have especific variable. For example:

body enter an area2d and fires a signal.

I wanna check if body.has_variable(SomeVariable) for example.

:bust_in_silhouette: Reply From: Daniel Lewan

You could use methods from Object class

I suppose it’s not exacly what do you want but you can do this

if not body.get(SomeVariable) == null:
     # body has variable

However if you set SomeVariable to null this code will think that body don’t have this variable.

As workaround you could use dummy setget getter for SomeVariable and has_method() function

#body
var SomeVariable setget SomeVariable_get

func SomeVariable_get():
    return SomeVariable

# somewhere else

prints(body.has_method("SomeVariable_get") # true

Looking in Object Class link, found void get ( String property ) const and simply did:

if body.get("Variable"):
    #do stuff

haha, so simple, thanks for the link!

tiernich | 2016-04-15 15:45

if node.get("varName") is not good solution because you will get false even if variable is defined but it currently have false (or null) value.

kubecz3k | 2016-04-18 08:35

@kubecz3k in this specific case, this solution is still valid for me, but i get what you say and in other cases i could be in trouble not knowing this. Now i can use the answer you gave me bellow. Thanks!

tiernich | 2016-04-18 13:49

:bust_in_silhouette: Reply From: kubecz3k

The proper way to check this is to use inkeyword. Like for example:
if "varName" in get_parent(): print("varName is defined in parent!")

oh, ok, thanks for the info :slight_smile:

tiernich | 2016-04-18 13:44

I didn’t know about in keyword. It’s definitely proper way to do this. Thanks

Daniel Lewan | 2016-04-19 06:51

this one is the right answer, thx!

racascou | 2023-01-17 13:46