Here's the script, Also should I put the script in a local script or a normal one and where should I put it?
local DSS = game:GetService("DataStoreService") local datastore = DSS:GetDataStore("GeneralSaveData", "Players") function generateDataKey(player) local ret = "uid_" .. player.userId return ret end function generateDataTable(player) local dataTable = { Gold= player.leaderstats.Gold.Value, Fishies= player.leaderstats.Fishies.Value } return dataTable end function saveDataForPlayer(player) local key = generateDataKey(player) local data = generateDataTable(player) datastore:SetAsync(key, data) end function inputDataToPlayer(player, data) player.leaderstats.Gold.Value = data.Gold player.leaderstats.Fishies.Value = data.Fishies end function loadDataForPlayer(player) local key = generateDataKey(player) local data = datastore:GetAsync(key) inputDataToPlayer(player, data) end game.Players.PlayerAdded:Connect(function(player) loadDataForPlayer(player) --Load first thing when they join player.leaderstats.Fishies.Changed:Connect(function() saveDataForPlayer(player) --Save the data end) end) game.Players.PlayerRemoving:Connect(saveDataForPlayer) --Save data when the player leaves the game
A few critiques of why it may not be working... First you are not checking to see if you actually got a Datastore element in the first place, specifically here:
function inputDataToPlayer(player, data) player.leaderstats.Gold.Value = data.Gold player.leaderstats.Fishies.Value = data.Fishies end function loadDataForPlayer(player) local key = generateDataKey(player) local data = datastore:GetAsync(key) inputDataToPlayer(player, data) end
You are calling inputDataToPlayer without checking to see if data is nil, that will cause your loop to error out.
Also, here:
function saveDataForPlayer(player) local key = generateDataKey(player) local data = generateDataTable(player) datastore:SetAsync(key, data) end
You COULD do SetAsync, but instead you could check to see if that particular key already exists and instead do an UpdateAsync which is much faster. If the key doesn't exist yet, then you would be forced to do a SetAsync.