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;

5 comments
Pretty sure I've told you this before, the parent argument to Instance.new is deprecated. Another thing is you should use GetPlayers and not GetChildren.
Okay... that doesn't relate to the issue at hand... In fact, I quickly wrote up this script and that's simply a bad habit that's being worked on.
Not sure if this will fix your problem but try adding a pcall function
AlvinBlox has an amazing tutorial on DataStores though, here's the link, https://www.youtube.com/watch?v=tOOS9lMIYes
ew no