This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+18 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.

in Engine by (429 points)

2 Answers

+5 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
by (373 points)
selected by

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!

+56 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!")

by (1,299 points)
edited by

oh, ok, thanks for the info :)

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

this one is the right answer, thx!

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 Frequently asked questions and 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 [email protected] with your username.