``local datastore = game:GetService("DataStoreService") local data1 = datastore:GetDataStore("Data1") game.Players.PlayerAdded:Connect(function(player) local Data = Instance.new("Folder",player) Data.Name = "leaderstats" local cash = Instance.new("IntValue", Data) cash.Name = "Cash" cash.Value = data1:GetAsync(player.UserId) or 10 end)
game.Players.PlayerRemoving:Connect(function() data1:GetAsync(player.UserId, cash.Value) end)
-- For auto saving if you have a auto saved data while wait(60) do -- to make request per minute less and worked. data1:GetAsync(player.UserId, cash.Value) end
As has been mentioned, you need to use a code block in future to make your question easier to understand, but anyway:
You have the following code
local datastore = game:GetService("DataStoreService") local data1 = datastore:GetDataStore("Data1") game.Players.PlayerAdded:Connect(function(player) local Data = Instance.new("Folder", player) Data.Name = "leaderstats" local cash = Instance.new("IntValue", Data) cash.Name = "Cash" cash.Value = data1:GetAsync(player.UserId) or 10 end) game.Players.PlayerRemoving:Connect(function() data1:GetAsync(player.UserId, cash.Value) end)
So, theres two reasons this wont be working - first one is pretty simple. When the player is leaving, you are trying to use GetAsync to store data. Instead you should use the SetAsync function.
Secondly, you need to think about scopes. Scopes are locations in the code where variables can/cannot be accessed. In your case, both the PlayerAdded event function and the PlayerRemoving event function are scopes. Variables that you assign inside a scope cannot be accessed outside of that scope.
Hence, the player and cash variables that you use in PlayerAdded are not accessible in the PlayerRemoving function.
To fix this you can make the following changes:
local datastore = game:GetService("DataStoreService") local data1 = datastore:GetDataStore("Data1") game.Players.PlayerAdded:Connect(function(player) local Data = Instance.new("Folder", player) Data.Name = "leaderstats" local cash = Instance.new("IntValue", Data) cash.Name = "Cash" cash.Value = data1:GetAsync(player.UserId) or 10 end) game.Players.PlayerRemoving:Connect(function(player) local cash = player.leaderstats.cash data1:SetAsync(player.UserId, cash.Value) end)