How to get edited_scene_tree in EditorPlugin

Godot Version

4.2.1

Question

I have a plugin which is loaded in my project. I also have a scene with some nodes. The root node is called “game”.

When I try to access the root node of the currently edited scene via get_editor_interface().get_edited_scene_root() in the _enter_tree() function, it returns null. When I try to do the same in _ready(), it also returns null.
Full code:

@tool
extends EditorPlugin

var editor_interface: EditorInterface
var scene_root: Node

func _enter_tree():
    editor_interface = get_editor_interface()
    scene_root = editor_interface.get_edited_scene_root()

func _ready():
    pass

I tried multiple different strategies, looking for a signal (scene_changed? scene_loaded?) or even just checking in _process() until the scene is loaded - but somehow it only got executed once.
I also tried call_deferred() calling a function to get it, which didn’t change a thing. I am beyond frustrated. Why is it so hard to get the edited_scene_tree when that is the most likely thing a plugin could do? How can I achieve it? Is it even possible?

Is your script an @tool? I know it probably is, but just confirming.

This is the code I’m using:

		print("Root is:")
		print(EditorInterface.get_edited_scene_root())

I have a slightly weird setup, but I’m calling it in _parse_property of an EditorInspectorPlugin.

Yes, my script starts with
@tool
extends EditorPlugin

Sadly that doesn’t apply in my case. EditorPlugin has no _parse_property() function.

If you set it in _enter_tree() or _ready() it will only get the edited scene if you have one scene open and disable and enable the plugin again because the plugin gets enabled before loading the last opened scene when opening Godot. If you disable and enable it again with one scene open then it works because there’s already a scene when enabling it.

Connect to the EditorPlugin.scene_changed signal to be able to get the current scene root when Godot opens.

For example:

@tool
extends EditorPlugin


func _enter_tree() -> void:
	scene_changed.connect(func(new_root:Node):
		if new_root:
			printt('Scene changed to: ', new_root.name)
	)