Hello, i have a problem with my leaderstats script. It doesnt save my data with an error saying "attempt to index nil with 'Coins', the name of my currency. heres my code, my leaderstats is in a different script
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 = { Coins = player.leaderstats.Coins.Value, Clicks = player.leaderstats.Clicks.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.Coins.Value = data.Coins player.leaderstats.Clicks.Value = data.Clicks 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.Coins.Changed:connect(function() saveDataForPlayer(player) --Save the data when Wins changes value end) end)
game.Players.PlayerRemoving:connect(saveDataForPlayer)
if you can help, please tell me whats wrong with this code, sruffolo
Firstly, please use the Lua Formatter. Secondly, did you make a leaderstat named coins? You should make a game:BindToClose function that makes the leaderstats save before the server shuts down. You should use a pcall if you want the script to stay working.
game:BindToClose(function() for _, plr in pairs(game:GetService("Players"):GetPlayers()) do local success, errorMessage = pcall(function() saveDataForPlayer(plr) end) -- wrap function in pcall so script doesnt break :) end wait(20) -- wait few seconds to process end)
If this helps you, please upvote this answer. Thanks!