trying to get the leaderstats to save but its not working, the cash does go up but, the data isn't saving. is there anything im missing?
game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("IntValue",player) leaderstats.Name = "leaderstats" leaderstats.Parent = player local cash = Instance.new("IntValue",leaderstats) cash.Name = "RPCash" cash.Value = 0 cash.Parent = leaderstats local reward = 1 while true do wait(5) cash.Value = cash.Value + reward end DataStore = game:GetService("DataStoreService"):GetDataStore("SaveCash") local Key = player.userId local Data = DataStore:GetAsync(Key) if Data then cash.Value = Data end end) game.Players.ChildRemoved:connect(function(Player) local Key = Player.userId DataStore:SetAsync(Key,Player.leaderstats.Cash.Value) end)
Wiki's definition on PlayerRemoving:
The PlayerRemoving event fires right before a
Player
is leaves the game. This event fires beforeInstance/ChildRemoved|ChildRemoved
does onPlayers
, and behaves somewhat similarly toInstance/DescendantRemoving
. Since event fires before the actual removal of aPlayer
, this event is useful to store player data using aGlobalDataStore
.
Meaning the data wasn't saving because the player had already left. Simply switch the events, and referring back to my comments, please indent your code properly and always use local variables.
local cashSave = game:GetService("DataStoreService"):GetDataStore("SaveCash") -- No need to declare this variable each time a player joins. local Players = game:GetService("Players") local reward = 1 -- Same here. Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("IntValue") leaderstats.Name = "leaderstats" leaderstats.Parent = player local cash = Instance.new("IntValue") cash.Name = "RPCash" cash.Value = cashSave:GetAsync(player.UserId) cash.Parent = leaderstats end) Players.PlayerRemoving:Connect(function(player) cashSave:UpdateAsync(player.UserId, function(previous) -- You're simply updating the data store, use this instead -- 'previous' is just the old data return player.leaderstats.RPCash.Value -- function must return what you want to update with end) end) while true do -- much better than having individual loops wait(5) for _, player in ipairs(Players:GetPlayers()) do player.leaderstats.RPCash.Value = player.leaderstats.RPCash.Value + reward end end
Here is some information on :UpdateAsync()
, and here for a tutorial written by Link150 on how to properly save your player's data.