This is the script that runs in my “ship” collection, which is where the contents of the cargo should be loaded as physical objects. It works perfectly the first time (currently the cargo array in the save file contains 1 value: “Crate” and 1 crate is being physically loaded in the ship)
function init(self)
savefile_path = sys.get_save_file("StellarSalvagers", "SaveFile")--defines file path where game data is saved
SavedData = sys.load(savefile_path)--loads the data file and assigns it to a variable
inventory = {}--creates inventory array incase there isnt a saved one
cargo = {}--creates cargo array incase there isnt a saved one
if SavedData.inventory ~= nil then
inventory = json.decode(SavedData.inventory)--loads inventory from saved data or create a new array if there's not one saved
end
if SavedData.inventory == nil then
print("Inventory is nil")
end
for i =1,#inventory do--prints the entire inventory array
print("Inventory Item",i,":",inventory[i])
end
if SavedData.cargo ~= nil then
cargo = json.decode(SavedData.cargo)--loads cargo from saved data or create a new array if there's not one saved
end
if SavedData.cargo == nil then
print("Cargo is nil")
end
for i =1,#cargo do--prints the entire cargo array
print("Cargo Item",i,":",cargo[i])
end
if #cargo < 15 then--wont continue adding items from the inventory if cargo is full (15 slots)
for i = 1, #inventory do--inserts each value from inv into cargo one at a time
NewItem = inventory[i]
table.insert(cargo, NewItem)
if #cargo >= 15 then
break
end
end
end
sys.save(savefile_path, {cargo = json.encode(cargo)})--saves the cargo array to the data file
end
I then load into the “level” collection where i can pick up crates, which adds them to the inventory array, then saves the inventory array to the save file just before the “ship” collection is loaded again.
Part of the player script that handles the inventory:
if message_id == hash("ItemPickedUp") then--(for the item picking up) if it receives a message from an object that it has been picked up
if #inventory < MaxSlots then --only runs if the number of objects in the inventory array is less than the number of max slots)
local itempickedup = message.objecturl
table.insert(inventory, itempickedup)--adds the item picked up to the inventory
sys.save(savefile_path, {inventory = json.encode(inventory)})--cant save arrays themselves, have to encode them first into a string to save them
end
end
This part is running as intended and the inventory array is correct, the only issue is that at this point, if i had 1 crate in cargo to start with, then loaded the “level” collection, picked up eg 2 crates, then loaded the “ship” collection again, it would load 2 crates, rather than 3. Im unsure what’s wrong here.