Strongly typed child querying

Godot Version

4.2

Question

Hi. Is it possible to have template functions? Or is there some other way to strongly type a single function to allow it to search for arbitrary child node class types?

I am basically hoping to add a function to my character scene that allows external scripts to query it’s child nodes using their script class types.

For example, if I have a scene called Robot who has two child nodes with scripts attached with the class_names HealthComponent and InventoryComponent, I would like a function on the Robots script to the effect of:

func getChildComponent(type: T) -> T:
    # Pseudo code:
    for each child
        if type of child equals type:
            return child
    return null
    # End pseudo code

Failing that, is there some way to obtain the name of a class without instantiating an instance of said class in a way that is strongly typed? If so the getChildComponent function could take a string, but at the call sites I could strongly type the code to obtain the class type string.

Kind regards, Aatwo.

i dont think you can pass types as arguments. wouldnt it be easier to save the children as variables in the robot-script. This would avoid looking each time through all the children to find one component

This is possible, however I want to have a solution that I can reuse across many entities with as little setup as possible while maximising type safety. For example, I could have a function that takes class names as a string, but this would become prone to errors. Apparently you can pass a type as a parameter and it goes into the function as a GDScript type, but there doesn’t appear to be any way to use that to obtain the actual class name.

I found a solution to this on reddit.

# Elsewhere
func get_child_component_or_null(type: GDScript) -> Node:
    for child in get_children():
        if is_instance_of(child, type):
            return child
    return null

This is great because you can call it using a class_name type directly. For example:

var healthComponent = get_child_component_or_null(HealthComponent)

where HealthComponent is the class_name.

2 Likes

Wow thats cool. Didnt know that works

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.