Idk why but it's not saving
local dataStore = game:GetService("DataStoreService") dataStore:GetDataStore("Cash") game.Players.PlayerAdded:Connect(function(plr) local leaderstats = Instance.new("Folder") leaderstats.Parent = plr leaderstats.Name = "leaderstats" cash = Instance.new("IntValue") cash.Name = "Cash" cash.Parent = leaderstats local data local success,err pcall(function() data = dataStore:GetAsync(plr.UserId) end) if success then cash.Value = data elseif err then warn(err) print("when plr joining saving data didnt work") end game.Players.PlayerRemoving:Connect(function(plr) local success,err pcall(function() dataStore:SetAsync(plr.UserId, plr.leaderstats.Cash.Value) end) if success then print("Worked saving") elseif err then warn(err) print("something went wrong saving data") end end) end)
The code below will not get the data store. Your code will throw an error as DataStoreService does not have a function called GetAsync or SetAsync.
local dataStore = game:GetService("DataStoreService") -- this is the service not the data store object dataStore:GetDataStore("Cash") -- this gets the cash data store but it is never used
The second problem is with the line. This is not assign the variables the values passed back from pcall. Use the assignment operator =
local success,err pcall(function()
Lastly you should not be be connecting a new PlayerRemoving event each time a player joins. This will stack causing your saves to fail.
game.Players.PlayerAdded:Connect(function(plr) -- this adds a new function to the event each time game.Players.PlayerRemoving:Connect(function(plr) end) end)
local dataStore = game:GetService("DataStoreService"):GetDataStore("Cash") game.Players.PlayerAdded:Connect(function(plr) local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" local cash = Instance.new("IntValue") cash.Name = "Cash" cash.Parent = leaderstats leaderstats.Parent = plr -- parent to game last local success, result = pcall(function() return dataStore:GetAsync(plr.UserId) -- return the value from the function call end) if success then cash.Value = result else -- only else is needed warn(result) -- result will hold the error message if there is one print("when plr joining saving data didnt work") end end) game.Players.PlayerRemoving:Connect(function(plr) local success,result = pcall(function() dataStore:SetAsync(plr.UserId, plr.leaderstats.Cash.Value) end) if success then print("Worked saving") else warn(result) print("something went wrong saving data") end end)
You should include a retry if one save/load fails.
Hope this helps. Please comment if you have any other questions about this code.