This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+1 vote

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)):

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)
Godot version v4.0.stable.official [92bee43ad]
in Engine by (17 points)
edited by

1 Answer

+1 vote

Here you'll find two of my answers have code examples, hope one of them suits your needs:

by (1,957 points)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.