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?