Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Darloth |
I want to write a function which can be reused to load any type of resource into an arbitrary typed array.
var array1: Array[DataType1]
var array2: Array[DataType2]
where DataType1 and DataType2 are both custom types in gdscript derived from Resource using class_name
if I write
var dataItem = load("res://data/someItem.tres")
how do I confirm that dataItem is of type1 or 2 without hardcoding references to those types? I want to do something like this:
func loadData(targetArray: Array, targetFilename: String, dataType: StringName):
var dataItem = load(targetFilename)
if(typeof(dataItem) == Type.fromString(dataType)):
targetArray.append(dataItem)
but obviously gdscript doesn’t support that level of reflection and everything is just an Object with some metadata at the engine level.
Is there a way I can make a generic load function or do I end up writing several similar ones so I can actually benefit from
if(dataItem is DataType1):
# do something
My end goal is to be able to write something like
loadData(weaponArray, "res://data/weapons/", "WeaponData")
loadData(vehicleArray, "res://data/vehicles/", "VehicleData")
...
and have it stay relatively type safe. It would be even better if I could just pass the type created by class_name itself instead of the StringName of the type, like so:
loadData(weaponArray, "res://data/weapons/", WeaponData)