How to Delete Save Data If Error Detected?

Godot Version

4.2.1

Question

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://game_data.save"

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


#func _ready() -> void:
    #create_time_records()


func create_time_records() -> void:
    if not SceneManager.levels:
        return
    
    for i in len(SceneManager.levels):
        time_records.append(0.0)
    
    load_data()


func save_data() -> void:
    var file = FileAccess.open(GAMEDATA_FILE_PATH, FileAccess.WRITE)
    file.store_var(time_records)
    file.store_var(has_played)
    file.store_var(last_level)
    file.store_var(unlocked_level)
    file.close()


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

Edit:
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 = Directory.new()
	if dir.open("user://") == OK:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			if dir.current_is_dir():
				print("Found directory: " + file_name)
			else:
				print("Found file: " + file_name)
				dir.remove(file_name)
			file_name = dir.get_next()

Hope this help.