How to change a scene's exported variable via tool mode?

84 Views Asked by At

I have a scene as such:

enter image description here

where the main scene has a show_title variable and before I export the game I run the following plugin:

tool
extends EditorExportPlugin
class_name CustomExportPlugin


func _export_begin(features, is_debug, path, flags):
    # do some checks before exporting
    ...

How do I set the show_title=true within the Main.tscn every time before exporting?

Note: I am using godot version 3.5

2

There are 2 best solutions below

2
On BEST ANSWER

Modifying an scene from a tool script

  • You load the scene.

    var my_scene := load("res://main.tscn") as PacketScene
    
  • You instance it (instantiate in Godot 4).

    var my_instance := my_scene.instance()
    
  • You modify the instance:

    my_instance.show_title = true
    
  • You package it again:

    my_scene = PackedScene.new()
    scene.pack(my_instance)
    
  • And save it:

    ResourceSaver.save(my_scene, "res://main.tscn")
    

Yes, this modifies the project. And no, EditorExportPlugin IN GODOT 3, does not make this any easier.

IN GODOT 4 you can override _begin_customize_resources to return true, and override _customize_resource to return the modified PackedScene. This way you don't have to save it, and thus the project is not modified.


What I would do

In the script on the root of main.tscn:

func _ready() -> void:
    show_title = true

If you need this set before _ready, you can do it in _init instead.

If that script is not a tool script, that won't happen in the editor. If it is, then you can check if the code is running in the editor with Engine.editor_hint (Engine.is_editor_hint() in Godot 4).

0
On

For anyone wondering, based on @Theraot's answer this is what the complete script looks like:

tool
extends EditorExportPlugin

const MAIN_SCENE_PATH="res://Main.tscn"

func _export_begin(features, is_debug, path, flags):
    
    var main_scene := preload(MAIN_SCENE_PATH) as PackedScene
    var new_instance := main_scene.instance()
    new_instance.show_title = true
    
    main_scene = PackedScene.new()
    main_scene.pack(new_instance)
    
    ResourceSaver.save(MAIN_SCENE_PATH, main_scene)