Is it possible to programmaticaly instantiate/edit nodes and keep them as scenes?

Godot Version

4.2.1 stable_linux


I want to know if there’s a way to populate a scene programmaticaly, but not while the game is running. I want to generate a level or map through code and be able to keep in the editor and modify it, replicate it, etc…
For example, if I’m making a board for a game, with hexagonal tiles in it, I need to not only place the tiles’ sprites, but also Marker2Ds for routing, maybe add (possibly randomized) enemies and objects, and so on. And if I modify the rules for generation or alter the tiles’ size/rotation, the map should adapt to it.
I’m new to Godot, and more inclined towards programming, but I understand that in other software artists have tools that let them do something like this, at least for the visual part, I don’t know about placing markers and such.

One thing I thought is that I could instantiate a node in the editor, and make a script that instantiates the things I want as children of it (at game runtime) and somehow save that scene, in that state, as a custom scene in the projects directory.
Something like:

for i in (1..10):
    for j in (1..10):
        tile = some_node_class
        add sprite2D child to tile, set it to some sprite
        add marker2D child to tile, set its position to vector2(i*100, j*100)
        if random_number == thing -> add enemy or loot child to tile
        add tile as child of this node
save the node's state as "map_board.tscn"

It doesn’t sound outlandish, but maybe it is?

You can create your scenes in code and set the object owners and save to file as a PackedScene. You can find the documentation and examples on that class.

1 Like

Thanks, that worked!
I wasn’t sure it was possible, but seems easier than expected. Now I have to actually get it to work properly, heh

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.