Last active
August 18, 2025 11:09
-
-
Save HungryProton/37cfd066234275dc6eac0a10784db5a7 to your computer and use it in GitHub Desktop.
Utility methods to find nodes by class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Returns the first child node of a given class. | |
## If deep_search is true, search the whole tree below this node. | |
static func find_child_with_class(root: Node, type: Variant, deep_search: bool = false) -> Node: | |
if not is_instance_valid(root): | |
return null | |
if is_instance_of(root, type): | |
return root | |
var candidates: Array[Node] = root.get_children() | |
while not candidates.is_empty(): | |
var candidate: Node = candidates.pop_back() | |
if is_instance_of(candidate, type): | |
return candidate | |
if deep_search: | |
candidates.append_array(candidate.get_children()) | |
return null | |
## Returns every child node of a given class. | |
## If deep_search is true, search the whole tree below this node. | |
static func find_children_with_class(root: Node, type: Variant, deep_search: bool = false) -> Array: | |
var result: Array = [] | |
if is_instance_of(root, type): | |
result.push_back(root) | |
var candidates: Array[Node] = root.get_children() | |
while not candidates.is_empty(): | |
var candidate: Node = candidates.pop_back() | |
if is_instance_of(candidate, type): | |
result.push_back(candidate) | |
if deep_search: | |
candidates.append_array(candidate.get_children()) | |
return result | |
## Returns the closest ancestor node with the given class | |
static func find_ancestor_with_class(root: Node, type: Variant) -> Node: | |
var parent: Node = root.get_parent() | |
while is_instance_valid(parent): | |
if is_instance_of(parent, type): | |
return parent | |
parent = parent.get_parent() | |
return null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment