Topic was automatically imported from the old Question2Answer platform.
Asked By
MythicalDesigner
Trying to implement saving and usually one of the key things i put in is File.new() but it seems the identifier was completely removed in 4x. as it says “identifier File not declared in the current scope.” How do you do it now? I don’t really know where to even start.
Ok, got the script in except it wont store a whole dictionary, how do you get it to store a dictionary?
MythicalDesigner | 2023-02-27 04:03
What does your current code look like? Post it (and format it for the forum) for some additional input.
jgodfrey | 2023-02-27 14:09
var data = {"number": 1, "string": "test" }
func save(content):
var file = FileAccess.open(path,FileAccess.WRITE)
file.store_string(content)
file = null
func load_game():
var file = FileAccess.open(path,FileAccess.READ)
var content = file.get_as_text()
return content
func _ready():
save(data)
print(load_game())
MythicalDesigner | 2023-02-27 18:07
Minimally, you can change your save() and load_game() functions to use store_var() and get_var(), which will allow you to read/write any Variant type. That’ll do what you want, but the save file contents won’t be readable via a text editor (it’ll be binary data) - which may be an advantage. If you want a “readable” file, you can convert your Dictionary to JSON and then use store_line() and get_line() to write/read that data.
func save(content):
var file = FileAccess.open(path,FileAccess.WRITE)
file.store_var(content)
file = null
func load_game():
var file = FileAccess.open(path,FileAccess.READ)
var content = file.get_var()
return content
jgodfrey | 2023-02-27 18:34
I totally didn’t think about file.get_var(). Now it works, thank you very much!
if you want to do it like in 3.5, and export a dictionary to a readable file, JSON does not support all var types.
you can export to plain text with var_to_string then load with string_to_var,
like this:
export:
file.store_line(var_to_str(content))
import:
file = FileAccess.open(savedir, FileAccess.READ) content = file.get_as_text() error = str_to_var(content) if error != null: var data_received = error if typeof(data_received) == TYPE_DICTIONARY: print(data_received) # Prints dictionary else: print("Unexpected data")