How to save and load without unpredictable crashes

Godot Version

Godot mono 4.2.2

Question

Whenever I call ChangeScene() it has a high chance of crashing

A note I have discovered since I posted this is that this is almost a guarentee if it is doen in the first few seconds of the game running.

These are the functions:

public void Save()
{
using var saveGame = FileAccess.Open(“user://savegame.tscn”, FileAccess.ModeFlags.Write);
var SaveState = new PackedScene();
SaveState.Pack(GetTree().Root.GetChild(0));
ResourceSaver.Save(SaveState, “user://savegame.tscn”);
}
public void Load()
{
if (!FileAccess.FileExists(“user://savegame.tscn”))
{
return; // Error! We don’t have a save to load.
}
using var saveGame = FileAccess.Open(“user://savegame.tscn”, FileAccess.ModeFlags.Read);
// PackedScene LoadedState = ResourceLoader.Load(“user://savegame.tscn”) as PackedScene;
// (item as Node2D).Position = new(100000000, 100000000);
try
{
GetTree().ChangeSceneToFile(“user://savegame.tscn”);
}
catch
{

	}
}
1 Like