I am trying to create a plugin that needs to change code inside Shader files. I am being able to edit the files using the Resource Loader and Saver. I have tried to use the FileAccess method and it also works.
My problem comes to when the file is opened in the Shader Editor window. Edited files using the Resource Loader and Saver do not get updated at all if they are opened in the Shader Editor, and using the FileAccess the developer needs to minimize and maximize Godot for it to ask to update the files from memory.
Is there a way to make it so I can edit the files and they get synced in the editor?
The shader editor dock is not exposed to scripting so it was kinda tricky but it’s possible:
@tool
extends EditorScript
func _run() -> void:
var path = "res://my_shader.gdshader"
# Load the shader skipping the cache
var shader = ResourceLoader.load(path, "", ResourceLoader.CACHE_MODE_IGNORE_DEEP) as Shader
# Edit the shader
shader.code += "\n // Test"
# Save the shader
var err = ResourceSaver.save(shader, path)
print(error_string(err))
# Emit a fake "file_removed" signal so the Shader Editor closes the edited shader if needed
var fs_dock = EditorInterface.get_file_system_dock()
fs_dock.file_removed.emit(path)
# Re-import the saved shader
var fs = EditorInterface.get_resource_filesystem()
fs.reimport_files([path])
# Edit the shader by loading it again after re-importing it
EditorInterface.edit_resource(load(path))
The problem is that you’ll need to load the shader skipping the editor’s cached one (the one already opened) and tell the shader editor dock to “update” the old opened one with the new saved one which are different objects. I had to emit a fake FileSystemDock.file_removed signal so the shader editor dock closes the one opened. Force a re-import of the new saved shader so the editor removes its cached one from the cache (it throws an error in the output dock but it works fine). And edit the resource so it gets opened again but loading the one on disk so the editor does not treat it as two different objects (the in-memory saved one and the on disk saved one)
Thank you so much, I have been going around this problem for some time and you found the solution. I still have to fix some problems, as that solution makes it so all files that were changed with that method get opened, even if they were closed. Since my tool updates a lot of files at the same time, I had like 20 files open at the same time haha. But it’s a very good start, thx