Loading and Saving data on scene entry

Godot 4.1.stable

Hi, i’ve been trying to save and load a variable so that when the scene is opened,
depending on the value of the variable (n), a sprite (egg) is changed.
This is so that when my “egg” is hatched, and i go to see its stats in a different scene, when I return it is still hatched and not an egg.
Here is My code for the scene with the egg.

extends Node2D
var save_path = “user://variable.save”
@onready var tip1 = $tip1
@onready var egg = $Egg
@onready var egg_crack = $AudioStreamPlayer
@onready var egg_crack2 = $AudioStreamPlayer2
@onready var egg_crack3 = $AudioStreamPlayer3
var n = 1
var x = 1
var crack = 1

func _ready():
(this is where i’d like the load function to be called)
if n == 2:
egg.texture = load(“res://assets/pet_sprites/egg.png”)
else:
egg.texture = load(“res://assets/pet_sprites/newborn.png”)

func _process(_delta):
pass

func _on_button_pressed():
if crack == 1:
$Egg/AnimationPlayer.play(“crack1”)
egg_crack.play()
crack = 2
else:
if crack == 2:
$Egg/AnimationPlayer.play(“crack2”)
$tip1.hide()
egg_crack2.play()
crack = 3

		$Timer.start(1)

func _on_timer_timeout():
$AudioStreamPlayer3.play()
$Timer.stop()
$Egg/AnimationPlayer.play(“hatch”)
$tip2.show()
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“wobble”)
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“wobble2”)
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“wobble3”)
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“wobble2”)
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“move”)
await get_tree().create_timer(1).timeout
$Egg/AnimationPlayer.play(“idle”)
$tip2.hide()
(this is where i’d like the a save function to be called.)

func _on_stat_button_pressed():
get_tree().change_scene_to_file(“res://stat_menu.tscn”)

Please comment how to save and load the “n” variable,
possibly using a txt file if needed.

please use this for code

Bildschirmfoto 2023-12-30 um 20.20.33

example

func _on_timer_timeout():
      $AudioStreamPlayer3.play()
      $Timer.stop()
1 Like

i always recommend checking this save and load plugin github.com/AdamKormos/SaveMadeEasy , all you need to do is to enable the plugin, and use SaveSystem.get_var("the_variable","") to get the_variable from Save Data
and SaveSystem.set_var("the_variable_you_want_to_get","abc") to set the_variable into the Save Data, easy and simple

1 Like

Hi, i was wondering where you set the variable, as in where do you put the value you want to set it to.

Thanks for the help.

just set it like this SaveSystem.set_var("player_name","abc")