How do I check the type of a loaded custom resource?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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)
:bust_in_silhouette: Reply From: zhyrin

Here you’ll find two of my answers have code examples, hope one of them suits your needs: https://forum.godotengine.org/147024/type-type-hint

The one where you build your own type checker using get_script() is probably closest to what I want here, and I think it will work. I’ll mark this as best answer if nobody else has any even better ideas in a while, thanks.

Darloth | 2023-03-22 15:04