0 votes


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"):

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 (15 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,313 points)
selected by
+1 vote

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,236 points)

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

