+1 vote


so in my game I have areas that will damage whoever enters them (players, AI, ...)
I do use collision layers to make sure that only players and AI, and so on, are detected.
But I still want to make sure, that whatever entered the trigger actually has a damage method. (in case I forget to configure the layers)

So right now I am doing:

func _on_body_entered(body):
    if body.has_method("_on_take_damage"):

I was wondering if this is the best way to do this.
Especially, I wondered about the performance of has_method()
Another way of doing it would be:

func _on_body_entered(body):
    if body.is_in_group("damage"):

Perhaps is_in_group() is faster than checking has_method()?

I would like to know what the best way of doing this might be, perhaps something else I haven't considered yet?

Thank you.

in Engine by (16 points)

2 Answers

+3 votes
Best answer

This is not something you should be worrying about. Write code that works for you and let performance be a problem if/when it ever becomes a problem. In practice, you're never going to see a difference, so you're wasting time trying to "optimize" what doesn't need fixing.

by (21,940 points)
selected by
+2 votes

You should listen to kidscancode, he manages the really good eponymous youtube channel. It's a great resource.

I just wanted to add that the has_method approach is called duck typing and is very much a valid approach. After all, if you've defined a method _on_take_damage, wouldn't you want to call it whenever taking damage is appropriate? If you use the group approach, then each time you add a _on_take_damage method to a node you must remember to also add it to the group, and if you don't you're in for a painful bit of debugging.

by (1,244 points)

Thanks for the additional information.
Coming from languages like C++, I was unsure if using reflection like this would be considered bad practice.

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.