Saving a Typed Array and Loading it as a Typed Array using FileAccess

Godot Version

4.2

Question

I am trying to save an Array[Switch] to a file using store_var() and FileAccess. However, when loading it back it comes back as an Array.

## Saves switches to the file specified in SAVE_PATH
func save_switches() -> void:
	var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
	
	file.store_var(switches)
	file.close()

## Loads switches from the file specified in SAVE_PATH
func load_switches() -> void:
	if (FileAccess.file_exists(SAVE_PATH)):
		var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
		
		var encoded_array : Array = file.get_var()
		
		for encoded_switch : EncodedObjectAsID in encoded_array:
			switches.append(instance_from_id(encoded_switch.object_id))
		
		file.close()
	else: print("Unable to find switches file to load")

You defined the variable encoded_array as an Array. That is why it is loaded as an untyped Array.
Try:
var encoded_array : Array[Switch] = file.get_var(true)

I believe you need the true to decode objects.
However I am not sure weather get_var() can load typed arrays.
It may load variant type array without giving you an error.
So I would check to make sure you are getting the type that you want.

I changed my approach to the issue.

Instead of saving and loading it through store_var() I am using store_text() and get_as_text(), to write to the file I map the array into a Dictionary and JSON.stringify() it, and then to read I just JSON.parse_string() on the file data and map it to the Array I need. Which seems to work.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.