Topic was automatically imported from the old Question2Answer platform.
Asked By
DasCapschen
Hi,
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"):
body._on_take_damage(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"):
body._on_take_damage(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?
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.
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.
Thanks for the additional information.
Coming from languages like C++, I was unsure if using reflection like this would be considered bad practice.