Godot Version
4.3
Question
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?
Any insights would be appreciated!
That is an impressive amount of casting!
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]
Can you show Groups.Values.ENEMIES
’ value?
1 Like
Sounds like you’ve hit this issue Less strict design for typed arrays · Issue #73005 · godotengine/godot · GitHub
You should be able to use assign
to work around the issue.
var enemy_nodes: Array[Node] = get_tree().get_nodes_in_group(str(Groups.Values.ENEMIES))
var enemies: Array[Enemy] = []
enemies.assign(enemy_nodes)
1 Like
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.