+1 vote

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?

in Engine by (29 points)

1 Answer

+1 vote

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
    self.add_child(node)

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.

by (1,445 points)
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 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 webmaster@godotengine.org with your username.