Godot Version
4.3
Question
I am working on creating a save system for my project and I have created a basic save system to save my players inventory.
extends Node
const SAVE_PATH: String = "res://savegame.bin"
func save_inventory() -> void:
var file = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
var inventoryData: Dictionary = {}
var inventoryGrid = GUI.inventoryMenu.get_child(0).get_child(1)
for i in inventoryGrid.get_child_count():
var slot_index = i
var item_data
var item_data_count
if inventoryGrid.get_child(i).get_child_count() <= 0:
item_data = null
item_data_count = 0
inventoryData[slot_index] = {item_data: item_data_count}
elif inventoryGrid.get_child(i).get_child_count() > 0:
#slot has an item
item_data = inventoryGrid.get_child(i).get_child(0).data
item_data_count = inventoryGrid.get_child(i).get_child(0).itemCount
inventoryData[slot_index] = {item_data.itemName: item_data_count}
var inventoryJSTR = JSON.stringify(inventoryData)
file.store_line(inventoryJSTR)
print("saved")
func load_inventory() -> void:
var file = FileAccess.open(SAVE_PATH, FileAccess.READ)
if !file:
return
if file == null:
return
if FileAccess.file_exists(SAVE_PATH) == true:
if not file.eof_reached():
var current_line = JSON.parse_string(file.get_line())
if current_line:
var inventoryGrid = GUI.inventoryMenu.get_child(0).get_child(1)
for index in current_line:
for item in current_line[index]:
if item != str("<null>"):
var inventoryItem = InventoryItem.new()
inventoryItem.init(Game.items[item])
if inventoryGrid.get_child(int(index)).get_child_count() <= 0:
inventoryGrid.get_child(int(index)).add_child(inventoryItem)
inventoryGrid.get_child(int(index)).get_child(0).itemCount = int(current_line[index].get(item))
print("loaded")
Example of Save File:
{“0”:{“”:0},“1”:{“”:0},“2”:{“”:0},“3”:{“”:0},“4”:{“Purple Berry”:5},“5”:{“”:0},“6”:{“”:0},“7”:{“”:0},“8”:{“”:0},“9”:{“”:0},“10”:{“”:0},“11”:{“”:0},“12”:{“”:0},“13”:{“Purple Berry”:4},“14”:{“”:0},“15”:{“”:0},“16”:{“”:0},“17”:{“”:0},“18”:{“”:0},“19”:{“”:0},“20”:{“”:0},“21”:{“”:0},“22”:{“”:0},“23”:{“”:0},“24”:{“”:0},“25”:{“”:0},“26”:{“Purple Berry”:6},“27”:{“”:0},“28”:{“”:0},“29”:{“”:0}}
My question is, if I wanted to store more lines of information to be saved; for example to save the hotbar inventory or equipment slots, what is the best way to store multiple lines in a JSON file? Or how should I organize the save file so i can easily get the line i need to load and not need to keep track which line is what in the JSON? Can I create a label or a tag for each line to easily get what i need?