Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Creating a data store script. How can I prevent loss of player data?

Asked by
RAYAN1565 691 Moderation Voter
5 years ago
Edited 5 years ago

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;
0
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. User#19524 175 — 5y
2
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. RAYAN1565 691 — 5y
0
Not sure if this will fix your problem but try adding a pcall function YouSNICKER 131 — 5y
0
AlvinBlox has an amazing tutorial on DataStores though, here's the link, https://www.youtube.com/watch?v=tOOS9lMIYes YouSNICKER 131 — 5y
0
ew no User#19524 175 — 5y

1 answer

Log in to vote
1
Answered by
valchip 789 Moderation Voter
5 years ago

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

Ad

Answer this question