How to Delete Save Data If Error Detected?

Godot Version



When the game starts, it will check the save data. If an error is detected (The array is not the same, wrong variable type, etc), it will delete the data to avoid it being used.

How do I write that?

This is my script that I have written in GD4. Right now, I only return if the array of time records are not the same.

extends Node

const GAMEDATA_FILE_PATH = "user://"

var has_played: bool = false
var last_level: int = 0
var unlocked_level: int = 0
var time_records: Array[float] = []

#func _ready() -> void:

func create_time_records() -> void:
    if not SceneManager.levels:
    for i in len(SceneManager.levels):

func save_data() -> void:
    var file =, FileAccess.WRITE)

func load_data() -> void:
    if not FileAccess.file_exists(GAMEDATA_FILE_PATH):
    var file =, FileAccess.READ)
    var temp_time_records: Array[float] = file.get_var()
    if temp_time_records.size() != time_records.size():
    time_records = temp_time_records
    has_played = file.get_var()
    last_level = file.get_var()
    unlocked_level = file.get_var()

However, I also got some suggestions to overwrite the data or move the bad data to another folder for better practice.

You could return true/false for load_data or make your own enum/int of errors codes.

I forgot to mention something.

I’m working on this because I want to delete/overwrite the old save of the game I released long ago.

I’m currently making the 2.0 with more levels and stuff. So I want to delete/overwrite the old save data through script.

I can’t just ask the players to manually delete the save data.

After some experiments, I’ve decided to rename the file path instead of deleting the old save data.

You see, I tried to read the old save data in Godot 4. But the serialization format has changed. You can only read it in Godot 3, not GD4.

So renaming the file path is the solution.

In my game, if I detect a different version and a flag is set to true, I clear all user data files with this code (Godot 3.5.3):

func clear_data_file():
	# Clear all files in user data path
	var dir =
	if"user://") == OK:
		var file_name = dir.get_next()
		while file_name != "":
			if dir.current_is_dir():
				print("Found directory: " + file_name)
				print("Found file: " + file_name)
			file_name = dir.get_next()

Hope this help.