I’m encountering a runtime error when trying to assign an Array[Enemy] to a variable of the same type in GDScript.
Here’s the code:
func get_enemies() -> Array[Enemy]:
var enemies:= Array( \
get_tree().get_nodes_in_group(str(Groups.Values.ENEMIES)) \
.map(func(node:Node): return node as Enemy) \
, TYPE_OBJECT, "Node", Enemy) as Array[Enemy]
return enemies
The error message I get at runtime is:
“Trying to assign an array of type ‘Array[Enemy]’ to a variable of type ‘Array[Enemy]’”
I expected this to work since the array should contain only Enemy instances. What could be causing this issue? Am I misunderstanding how typed arrays work in GDScript?
Do you intend to use the .map with as to introduce null elements to the array or do you only expect Enemy type elements? If you don’t expect null elements, have you tried this?
func get_enemies() -> Array[Enemy]:
return get_tree().get_nodes_in_group(str(Groups.Values.ENEMIES)) as Array[Enemy]
The code I had now works, it feels like it might have been related to running the method before every dependencies were in the tree.
The error message was very misleading. As the cast should have been a valid operation and I could even see the source array not being empty while debugging.