+11 votes

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.

asked Apr 15, 2016 in Engine by tiernich (423 points)

2 Answers

+2 votes
Best answer

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

var SomeVariable setget SomeVariable_get

func SomeVariable_get():
    return SomeVariable

# somewhere else

prints(body.has_method("SomeVariable_get") # true
answered Apr 15, 2016 by Daniel Lewan (364 points)
selected Apr 15, 2016 by tiernich

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!

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 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!

+33 votes

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

answered Apr 18, 2016 by kubecz3k (1,267 points)
edited Apr 18, 2016 by kubecz3k

oh, ok, thanks for the info :)

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

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.