I clicked on a part that increases my cash in the leaderstats. It worked, but as soon as I rejoin the game, my cash is back to the original one. The coins originally is 180, but as I clicked the part, it changed to 280. The data wasn’t being saved. The data store testing is in studio, not in a real game.
Code:
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local playerCoinsDataStore = DataStoreService:GetDataStore("PlayerDataStore", "PlayerCoins")
Players.PlayerAdded:Connect(function(plr)
local folder = Instance.new("Folder")
folder.Name = "leaderstats"
folder.Parent = plr
local intValue = Instance.new("IntValue")
intValue.Name = "Coins"
intValue.Parent = folder
local coins
local success, currentCoins = pcall(function()
coins = playerCoinsDataStore:GetAsync(plr.UserId)
end)
if success then
intValue.Value = coins
print(coins)
else
warn(currentCoins)
end
end)
Players.PlayerRemoving:Connect(function(plr)
local success, errorMessage = pcall(function()
playerCoinsDataStore:SetAsync(plr.UserId, plr.leaderstats.Coins.Value)
end)
if success then
print(errorMessage)
else
print(errorMessage)
end
end)
At least to me, your script appears to be fine. I believe the issue is probably the clickable part. If the clickable part is changing the coins value via a local script, it will not update on the server side. Ensure that the script changing the value is in an actual script and not a local script.
How are you exiting the studio test? Are you just pressing stop? Cause i could be wrong here but maybe that doesnt fire PlayerRemoving try just leaving the game inside the studio test instead of pressing stop.
You might want to also save the player data when the game is bound to close (which is what happens when servers are shutdown or you stop the game in studio).
game:BindToClose(function()
for _, plr in pairs(Players:GetPlayers()) do
local success, errorMessage = pcall(function()
playerCoinsDataStore:SetAsync(plr.UserId, plr.leaderstats.Coins.Value)
end)
if success then
print(errorMessage)
else
print(errorMessage)
end
end
end)
Yeah I was going to mention something about this as well PlayerRemoving is good but not always 100% reliable a lot of games do auto saves x amount of time or save data after a action with cool down.
I do believe it’s because you’ve got the leader stats in the plr when I player gets removed it’ll also get rid of the leaderstat so if you want playerremoving to work put leaderstat in replicatedstorage then delete it once the save is successful. Sorry for bad grammar writing this on my phone.
It will still work if each individual player leaves, it’s just that in studio, when you stop the game, it registers as shutting down the server and may not fire the .PlayerLeaving event. You can find more info about :BindToClosehere on the official Roblox documentation site.