Persist state of instantiate for later loading

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Blueberry

Hi, I’m currently on implementing a save and load system.

In my game, I have torches and those have a decay timer of 10s and will be queue_free() after those 10 seconds.

Now iIcreated a torch by button click and want to set the timer to 10 at startup, but I want to save the torches individual decay timer to be able to show the time correct when I load up my game.

I tried several things with resource, instToDict and packed scene but always the current value of the decay timer when I click on save is not stored, it’s always the initial decay time of 10, when the game is loaded

Any idea is welcome.


var decay_time_left = 10

func _ready():
    $TorchDecayTime.wait_time = decay_time_left 

func _process(delta):
       decay_time_left -= decay_time_left
    $TorchCounter.text = str(decay_time_left)

func _on_torch_is_empty_timeout():

Save the PackedScene resource

var new_torch = load("res://items/consumables/torch.tscn").instantiate()
var packed_scene = )
packed_scene.pack(), "user://my_scenes.tscn")

Load the PackedScene resource

var packed_scene = load("user://my_scenes.tscn")
var my_scene = packed_scene.instantiate()
var new_torch = load("res://items/consumables/torch.tscn").instantiate()
var packed_scene = )
packed_scene.pack(), "user://my_scenes.tscn")

This code is creating a new scene, packing it into a resource and saving it; there’s no state to persist other than the one you’ve just created. Rather, one approach is to store the torches as a resource and export the decay time and use the ResourceSaver this way. Alternatively, have a dictionary (perhaps in a save resource?) and store the timer for each torch that way, saving (and then loading) the dictionary.

Here’s the doc for a good start: Saving games — Godot Engine (stable) documentation in English

GDquest have a repo with an example using a resource: GitHub - gdquest-demos/godot-demos-2022: Free and open-source Godot demos for learning, with guides and tutorials: 2022 edition.

spaceyjase | 2023-05-11 15:16

Okay thanks, I went for the second approach, store the timers in a dictionary. This worked fine.

By the way, do you know how I can create this scene in a tile_map?

tile_map.set_cell(0, Vector2i(x,y), MYPACKEDSCENE, Vector2i(0, 0)) 

Blueberry | 2023-05-11 16:05

Good stuff.

I think you mean to update the TileSet? I’m not sure how to do that, other than in the editor. Do you need to have the scene in the TileMap, versus just existing in the world at a tile location? For example, I’ve included placeholders in a tileset before and instanced scenes (e.g. enemies, doors) in the placeholder location; they look and function like they’re in the tilemap.

spaceyjase | 2023-05-12 11:50