My first data store script (shown below) I have ever attempted works perfectly. However, sometimes if I quickly leave the server after collecting money, my progress won't save. How can I prevent this from occurring? I've tried using the PlayerRemoving
event, but it seems to not work as desired. Does anyone here have a more effective solution to this or is this compromise to player data normal?
local dataStore = game:GetService("DataStoreService"); local data = dataStore:GetDataStore("EvilData"); game.Players.PlayerAdded:Connect(function(player) local leader = Instance.new("Folder"); leader.Parent = player; leader.Name = "leaderstats"; local money = Instance.new("IntValue"); money.Parent = leader; money.Name = "Money"; money.Value = data:GetAsync(player.UserId) or 0; data:SetAsync(player.UserId, money.Value); end); game.Players.PlayerRemoving:Connect(function(player) print("Saving data"); data:SetAsync(player.UserId, player.leaderstats.Money.Value); print("Data saved"); end); while true do wait(60); for _, v in pairs(game.Players:GetPlayers()) do local money = v.leaderstats.Money; data:SetAsync(v.UserId, money.Value); wait(); end; end;
You wrap the DataStoring when the player leaves in a pcall
. A pcall
is used to handle errors. Luckily this function is really easy to understand, here is a link to the wiki http://wiki.roblox.com/index.php?title=Global_namespace/Basic_functions#pcall. Also check out this devforum page I found, the guy who was answering the guy gave a pcall
example.
https://devforum.roblox.com/t/help-with-datastores/72001