Instantiated packedscene at runtime can't be cast to a derived class

Godot Version

v4.2.1

Question

I am trying to instantiate a packed scene at runtime.
The root of the scene is my custom type that extends StaticBody3D.
However no matter what I do my main scene seems only to recognize it as a StaticBody3D type and not my custom one.
Casting to the right type always ends with null.

Is there proper way to do this?
I only need to initialize a few parameters for it.

My function that instantiate the scene:

func _dummy():
	...
	for h in high.keys():
		var icon := ActiveObject.TEMPLATE.instantiate()
		var ic = icon as ActiveObject
		print(ic)        # <-- this shows null
		add_child(ic)
		...
		ic.set_data(high[h])

My custom class:

extends StaticBody3D
class_name ActiveObject

const TEMPLATE = preload("res://assets/icons/run.tscn")
...

Iā€™m looking at the docs and everything seems to be as it should be.

Is it possible that the type inference (:=) prohibits you from casting it to a derived type?

var icon := ActiveObject.TEMPLATE.instantiate()

Itā€™s a shot in the dark, but try changing := to =.

Alternatively, you could just explicitly define the type of TEMPLATE; with your use case it should never not be ActiveObject. Correct me if Iā€™m wrong on that.

const TEMPLATE: ActiveObject = preload("res://assets/icons/run.tscn")

Sorry I canā€™t help you more than that.

1 Like

I had a similar problem with Resources. It was fixed when i used ā€œloadā€ instead of ā€œpreloadā€. I think its because preload loads the resource before your custom-classes are defined

2 Likes

Unfortunately ā€˜ActiveObjectā€™ is created after ā€˜instantiateā€™ is called. Before that it is a PackedScene. But it was worth a shot :smiley:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.