![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | linkdude240 |
Is there a way to specify that a type is an argument in a function?
Let’s say I want to get all children of a type (I do), either derived or the specific type.
Here’s what I’m doing (which works!) If I write the following code, I am able to get nested descendant objects matching the type I specify. Adding the type hint “Type” does not work as “Type” is not a valid type for the type hint:
NodeUtilities.gd
# Returns all descendants in the node that inherits from the provided type
# Note: to use this the calling script should preload a script into a constant
# and provide the constant as the type parameter
# Also if the descendant inherits the type it will still return the descendant
func get_descendants_by_type(node: Node, type) -> Array:
var results:= []
if node.get_child_count() > 0:
for child in node.get_children():
results.append_array(get_descendants_by_type(child, type))
if child is type:
results.append(child)
return results
CharacterController.gd
extends KinematicBody2D
signal died
var health := 10
func _process(delta):
if health <= 0:
emit_signal("died")
func _ready():
for effect in NodeUtilities.get_descendants_by_type(self, DeathEffect):
self.connect("died", effect, "on_character_died")
DeathEffect.gd
extends AnimatedSprite
class_name DeathEffect
func on_character_died():
play()
Hopefully in my reduction to a minimally reproducible example I didn’t misspell or omit anything.
My problem is that in NodeUtilities.get_descendants_by_type()
I cannot properly provide a type hint to the type
parameter.
Converted my answer to a comment since it wasn’t what you were looking for.
…
Use a string instead and the function get_class():
func get_children_of_type(node: Node, type: String) -> Array:
var results:= []
if node.get_child_count() > 0:
for child in node.get_children():
if child.get_class() == type:
results.append(child)
return results
LeslieS | 2023-02-09 05:43
This is not exactly what OP asked: The is
operator will not check whether its the exact same class, but whether the given instance is assignable to that class.
MarcusRiemer | 2023-02-09 13:24
That is fair enough and accurate but in fact the poster does at least imply the exact class
children of a specific type (I do)
He says nothing about assignable or inherits from etc.
LeslieS | 2023-02-09 17:15
Ah sorry, I did mean “of or inheriting from”, but this is still a great solution for finding classes of a particular type!
I was more wondering about the type hint.
Edited my original post for clarity instead of re-wording my question in a comment lol
linkdude240 | 2023-02-09 23:15