Godot Version
v4.3.dev5.official [c9c17d6ca]
Question
Hello, I would like to make an EditorScript that creates a texture from my scene and that sets this texture as a member of a custom node, but I struggle to save and load the texture.
Here is a minimal example of how I proceed :
My scene consists of a single node with this script :
@tool
class_name MainScene extends Node2D
@export var texture:Texture
func create_texture() -> void :
var img:Image = Image.create(32,32,false, Image.FORMAT_RGBA8)
img.fill(Color.BLACK)
ResourceSaver.save(ImageTexture.create_from_image(img), "res://img.png")
texture = ResourceLoader.load("res://img.png")
I also have an EditorScript to run create_texture() :
@tool
extends EditorScript
func _run() -> void:
var main_node:MainScene = get_scene()
main_node.create_texture()
When I run the EditorScript, I get an error in the console (No loader found for resource: res://img.png (expected type: )
) and a img.png file appears in the filesystem but it seems errored because it has a red cross on it and and I get an error when I click on it (editor/editor_node.cpp:1239 - Condition "!res.is_valid()" is true. Returning: ERR_CANT_OPEN
). Also, when I look into my node inspector, I can see that it has no texture.
If I get the Godot file system to update (either by calling EditorInterface.get_resource_filesystem().scan()
, or by making Godot lose and regain focus), the img.png file does not have the red cross anymore and I can click on it.
If I re-run my script then, I get no error and the texture appears in the inspector.
All of this makes me guess that resource saving is not completely achieved after ResourceSaver.save() call, so immediate loading of the texture cannot be done. When I re-run the script, I can load a texture from img.png because the file already exists, but the texture that will be loaded into my node will be the previous version of the file.
So, here’s my question : what is the proper way to create a texture and attach it to a node from EditorScript ?