New Scene from code

Godot Version

4.4.1

Question

I am making a Tool that loads a json and creates the scene from its nodes (in the editor). How do I create a new Scene in godot like the Scene > New Scene functionality that already exists in Godot (which opens a new empty tab)?

image

You can simply create a base node, then add children to it.

For example:

var sprite2d

func _ready():
	var sprite2d = Sprite2D.new() # Create a new Sprite2D.
	add_child(sprite2d) # Add it as a child of this node.

addChild to what? i need a new tab for the new scene/node. Check out the screenshot.
I tried EditorInterface.Singleton.EditNode(newScene); but it does nothing..

Create a node or a whole branch, pack it into a packed scene object using PackedScene::pack(), save to resources folder using ResourceSaver and then open using EditorInterface::open_scene_from_path()

4 Likes

feels hacky, but ok, thnaks).. does godot do the same thing when you press the plus (new scene) button?

Nothing hacky about it, all straightforward api calls. The editor doesn’t do this when you press the plus button. I’m not sure that can be replicated in a straightforward way, other than plucking the plus button pressed signal callable out of the interface and calling it, which would indeed be hacky, but totally doable.

1 Like

The editor doesn’t do this when you press the plus button.

Don’t you mean the editor does this ? Superfluous negation ?

No, I meant what I wrote. The editor doesn’t do it. It initially doesn’t add any nodes (until you choose the scene “type”) and doesn’t pack/save/reload the scene when you create it.

Why are you using JSON instead of TRES? They’re both text formats. It seems like it would be easier to get whatever is creating your JSON file to begin with to instead create a TRES file. Then it’ll just open in the editor - no extra programming needed.

1 Like

Im using json cuz i have a game made in another engine that loads the UI from a json. I created a tool in Godot that loads and exports back to json, so i can visualize that ui and edit it. I had to choose between rewriting the game code for loading the ui from tres files or creating a tool in godot.

1 Like