In GDScript, how do you preload an Export-ed variable?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By marty

If you are using EXPORT to expose a variable in the inspector panel, how can you also preload it?

Something like this would be great, but sadly, it makes the GDScript parser cry foul:

onready var explosion_res = preload(export (PackedScene))

Is it me, or is it not possible to preload an exposed variables at all?

:bust_in_silhouette: Reply From: MysteryGM

Once you understand that Godot has two main types of classes, Resources and Nodes, you can easily use this to get what you want.

Since Godot’s scenes count as resources, we can easily make a node from any scene

#First get the resource from the editor
export (Resource) var resource = null

#You can only make new instances once the game starts
func _ready():
	#Now we can make a node from the resource
	var node = resource.instance()
	#We also need to place it somewhere in the tree

Now we can shorten this code using Godot’s Onready shortcut:

export(Resource) onready var node = self.add_child(node.instance())

1.) So what is happening here is we are makking a pointer to the resource called node.
2.) Then we make a instance from node and add it to the tree as a child of self.
3.) Lastly we set the pointer of node to point towards the node in the tree, we can do this because GDscript is dynamic; so it can switch between resource and node.