I don’t understand why though? what is our objective? I don’t see a reason to print the type like that. If you type the class name verbatim like that why not just make it a string? or use the node name self.name or just the self.get_class()
If you intend to spawn a specific type then use the ClassDB
var obj := ClassDB.instantiate("CollisionObject2D")
I have a utility function find_nodes_by_type(node: Node, type: Variant) -> Array[Node].
It does what the names suggests: it recursively searches the given node’s children for nodes of the given type and returns an array with all respective nodes.
Now consider the following use case:
var nodes: Array[CollisionObject2D] = find_nodes_by_type(some_node, CollisionObject2D)
It works as expected in the sense that it correctly retrieves all nodes with the given type.
However, it returns an Array[Node], not an Array[CollisionObject2D].
GDScript does not like this and will throw an error during runtime about trying to implicitly assign an Array[Node] to an Array[CollisionObject2D].
As a workaround you have to write:
var nodes: Array[CollisionObject2D] = 
This is a bit cumbersome, which is why I wanted to create a corresponding typed array in find_nodes_by_type using the typed array constructor so that further conversions are not necessary.
This constructor expects the type ID, the class name and optionally the script of the underlying type.
For script types, this is easy, but for native types I need the type name, which I can’t seem to get solely from the type parameter passed to the function.
And this brings us back to this question.
You may not like this, but I wonder if you could make a wrapper class that hosts the find function, and creates a dynamic script based on the type. Maybe throw some memorization so you don’t have to generate it dynamically every time? Although you will still have to define a return value.
Anyway I took a look at the source code and at the typed array function you mention, the script only has to be valid for the array type to work. That means it has be an instance. Although it’s not clear if it is used anywhere else.
Have you tried just casting with as instead of assigning?
Not sure how dynamically creating a script should help me there. I’m still lacking the native class name.
The typed array constructor needs the class name of the underlying native type and, if dealing with custom script types, a reference to the Script instance, not an instance of that script.
The underlying class name of a custom type can easily be retrieved using get_instance_base_type.
For native types it does not seem to be possible to retrieve the name without creating an instance first and then calling get_class() on that object.
Technically, it would be a workaround to create a temporary node instance for that purpose, but I’d rather use the Array.assign syntax.