most basic example:
world.tscn (main-scene)
extends Node2D
const MYLIST = preload("res://my_list.tscn")
func _ready() -> void:
var my_list = MYLIST.instantiate()
add_child(my_list)
my_list.initialization(["one", "two", "three"])
and my_list.tscn
extends Node2D
@onready var item_list: ItemList = $ItemList
func initialization(entries: Array[String]):
for entry in entries:
item_list.add_item(entry)
this gives me runtime-error: invalid type in function "initialization". The array of argument 1 (Array) does not have the same element type as the expected typed array argumen.
The argument i pass into my_list.initialization is clearly a Array[String] If i remove the type hint from the func declaration it works as expected.
Can someone explain whats wrong here? Thank you!
I do not know which version of Godot you are using, I would like to know so I can test in that specific version.
I can tell it is Godot 4 because you have typed
Arrays but the details have changed from version to version.If I recall correctly in Godot 4.0 this failed silently (no error, but you got an empty array), and after Godot 4.2 it seems to be working correctly. Thus, 4.1, probably?
Godot does not have typed
Arrayliterals (although in recent versions it will scan the contents of the array to find if the literal is compatible with a typedArray).So the
Arraygiven by["one", "two", "three"]is not aArray[String]but simply aArray, and your version of Godot might not be checking if it is compatible.So, aside from trying in a more recent version. I have three possible workarounds for you:
Revert the parameter to
Array:If you do not use a typed array
entries: Arrayyou would not have this problem. However you would be losing type information.Internally you can use
assing:Or convert the items to
String:Declare the
Array[String]in another line:If you declare a variable to be
Array[String]it might work:Declare the parameter as
PackedStringArray:If you declare the parameter like this:
entries: PackedStringArray, Godot should be able to do the conversion automatically. This is what I remember doing when I faced the problem.