Detecting Components within a Node with a Universal Function

(4.4.1 Stable)

I’m just starting to use components in my game, and they are cool! But how do I detect if a node has a component in an easy, universal way?

I have been searching and I found this reddit thread, but there was never a concrete answer, and it was 2 years ago.

My first idea was to for loop through every child of a node until it detects a node of a specific type. However, say the class_name of the component was health_component. I can’t make a function like func node_has_component(node, component_type) -> bool: because you can’t use a type as an argument.

I guess I could make every component called the same or inherit from the same class or something, but that has it’s own can of worms, like if I want a specific hitbox class that extends an Area3D.

I’m also aware of the is keyword, but the problem with that is I can’t make a universal function that passes node on one side of the is and component_type on the others, because type isn’t a type.

So my big question is: what solutions do you have for something like this in your game? Or should I just scrap composition and use an alternative?

Sorry for the long question

Have a look at my code snippet, which I believe will solve your issue.

1 Like

Put all the components into a group

Godot’s Object superclass has get_class() and is_class() which use strings to identify classes. is_class() will return true for subclasses that inherit from a class as well.

1 Like

This is very thorough. Tysm! I’ll have to take a look. I also looked at your GitHub issue, I agree

Unfortunately, get_class() and is_class() don’t return class_name and the function is kinda clunky. See this github issue. Imo I think it’s dumb that it works this way.

However, I did find a solution through some serious digging. For all future people with the same question: node.get_script().get_global_name() returns class_name.