How do I save stuff like number of coins on the player’s device and how do I retrieve it for a later session and how do I make it work for all platforms?
Take a look at sys.load (https://www.defold.com/ref/sys/#sys.load:filename) and sys.save (https://www.defold.com/ref/sys/#sys.save:filename-table)
There are some additional tips here that are helpful. I was having trouble saving data on Android before I found this topic:
DefSave was made to make this easier.
local gamedata = {}
local file_path = sys.get_save_file("my project", "gamedata")
local function broadcast()
msg.post("level:/controller#controller", "shields", {shields = shields})
msg.post("level:/controller#controller", "coins",{coins = coins})
msg.post("level:/gui#ui", "highscore",{highscore = highscore})
msg.post("level:/plane#plane", "missiles",{missiles = missiles})
end
function init(self)
local game_data= sys.load("gamedata")
if #game_data == 0 then
shields = 3-- as shown below
coins = 0
highscore = 0
missiles = 5
broadcast()
else
shields = game_data[1]--post to controller
coins = game_data[2] --post to controller
highscore = game_data[3] -- post a message to the score gui
missiles = game_data[4] -- post a message to the plane go
broadcast()
end
end
function on_message(self, message_id, message, sender)
if message_id == hash("shields") then
shields = shields + message.shields
elseif message_id == hash("coins") then
coins = coins + message.coins
elseif message_id == hash("highscore") then
highscore = highscore + message.highscore
elseif message_id == hash("missiles") then
missiles = missiles + message.missiles
end
end
function final(self)
table.insert(gamedata, 1, shields)
table.insert(gamedata, 2, coins)
table.insert(gamedata, 3, highscore)
table.insert(gamedata, 4, missiles)
sys.save(file_path, 'gamedata')
end
whenever i restart the session the length of gamedata is always zero how do it fix it
This line appears to be your problem. I believe Sys.load needs the filepath to find it. You could accomplish this by just inserting your file_path variable there:
local game_data= sys.load(file_path)
This will save the string “gamedata” to the file specified by file_path
. Shouldn’t you do sys.save(file_path, gamedata)
?
I think this should be sys.load(file_path)
just like @Gmanicus suggested.
thanks guys