I've made a custom resource and I want to load it as a default in an export variable so I've tried this:
extends Node2D
export(Resource) var custom_res=CUSTOM_RESOURCE.new()
and my custom resource script as such:
extends Resource
class_name CUSTOM_RESOURCE
export var data=10
but for some reason it doesn't seem to show up within the editor:
am I doing something wrong?
shouldn't the editor display the custom resource as default whenever the scene is instanced like this?:
That initialization is not running in the editor, only when the game starts.
You know the solution is tool
:
tool
extends Node2D
export(Resource) var custom_res=CUSTOM_RESOURCE.new()
And all that comes with it. For people finding this form search, be aware of Engine.editor_hint
.
Turns out the reason we need the initializer to run is because what we are setting (CUSTOM_RESOURCE.new()
) is not constant.
We can confirm that with a simple constant, for example:
export var x := 5
In that case the initializer didn't run in the editor per-se. Instead Godot set the constant was set as the default value when it parsed the script. And that is what we see in the Inspector.
So we want a constant value of our custom resource. Well, preload
is a constant expression (preload
is a keyword not a method). And yes, it is resolved while parsing. And yes, Godot will set it as default value, despite it not being a primitive type. Thus we can preload
a resource file and use that, for example:
export var custom_res:Resource = preload("res://new_resource.tres")
Which, of course, requires that we have resource file to preload
. We can create it from the context menu on the FileSystem by selecting "New Resource…", then picking our custom resource class, and a file name to save it.
Notice this differs from running the initializer in the editor in that:
tool
and all that comes with that.tool
, the default value remains (null
). So you will see the arrow to reset the value in the editor, and clicking it erases the value of the property.Gotcha: Everywhere you preload
the same resource file, you get the same resource object. Modifying it will modify it everywhere. Even across different scenes.