godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.14k stars 93 forks source link

Add a get_first_child_with_filter method to Node #10356

Open blackears opened 2 months ago

blackears commented 2 months ago

Describe the project you are working on

A 2D platformer where the player has to query the children of various objects it interacts with.

Describe the problem or limitation you are having in your project

One of the more powerful programming features Godot provides is composition. By adding children to a node, you can extend it's abilities without having to edit the code of the script itself. Unfortunately, is is also cumbersome to examine the children of a node.

For example, if an Area2D has its body_entered() signal called, I then want to check the body to see if it has one of my HitPoints objects and if so, adjust the hit points of that character. Right now, that involves calling get_children() on the node and then checking each one to see if it is the right object. It is tedious and error prone to have to keep writing this loop every time you want to look for a specific child of a node.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

I would like to see the following methods (or their equivalents) added to the Node object. Ever since Godot added Callable objects to the language, this provides a convenient way to filter nodes. The filter callable accepts a Node as input and returns a boolean true if it passes the check:

func get_first_child_with_filter(filter:Callable)->Node:
    for child:Node in get_children():
        if filter.call(child):
            return child
    return null

func get_children_with_filter(filter:Callable)->Array[Node]:
    var result:Array[Node]
    for child:Node in get_children():
        if filter.call(child):
            result.append(child)
    return result

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

Add the above methods to the Node object.

If this enhancement will not be used often, can it be worked around with a few lines of script?

The idea is to have this incorporated into the core so that it is not necessary to constantly rewrite these methods.

Is there a reason why this should be core and not an add-on in the asset library?

Should be a part of the Node object.

KoBeWi commented 2 months ago

That's basically #6889, no? Except you don't need to do get_children() I guess.

blackears commented 2 months ago

Yes, it's pretty similar.