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

How to Reliably Save with Datastores?

Asked by
INOOBE_YT 387 Moderation Voter
5 years ago

I made a datastore script that saves the IntValues in the leaderstats when the player leaves. This does not work because the contents in the player are removed when the event is fired, it says "Level is not a valid member of Player." How would I make it save the stats of the player without getting an error? Table for each plr?

2 answers

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Hi Noobe,

My data storage always works with the player leaving but, it was having issues with just one player being in the game and leaving. Which I found a simple solution for, and this is using the game's :BindToClose() method.

So, if a player leaves and there's other players in the server then the server doesn't shut down, in which case it's pretty simple to save the data right away by just storing it in a table or dictionary.

This is just an example from the game that I'm working on right now, but here it is:

function save_data(plr)
    local stats = plr:WaitForChild("Stats");
    local tab_to_save, key = {}, "user-"..plr.UserId;

    for _, stat in next, stats:GetChildren() do
        tab_to_save[stat.Name] = stat.Value;
    end

    pcall(function()
        ds:SetAsync(key, tab_to_save);
    end)

end

However, this gets somewhat complicated when the server shuts down and there isn't enough time for the game to save the data. In this case, I use the game's :BindToClose() method to have a callback function save the data right away as the server is shutting down.

This is also an example from the game that I'm working on right now:

function player_removing(plr)

    wait(0.001);

    if not is_closing_game then
        save_data(plr)
    end
end

game:BindToClose(function()
    is_closing_game = true;

    for _, plr in next, plrs:GetPlayers() do
        save_data(plr); 
    end
end)

The reason I wait for 0.001 seconds in the player_removing function is so that is_closing_game can update if the game is closing. So, the player_removing function doesn't try to save the data because the callback function in :BindToClose() is already on it.

Hope I helped and have a wonderful day/night.

Thanks,

Best regards,

~~ KingLoneCat

Ad
Log in to vote
0
Answered by 5 years ago

I typically keep an extra copy of everyone's data in ServerStorage for any data that needs to be stored. When a player joins the game just have it make them a Value in ServerStorage, and then when they leave you can save it and delete it.

Answer this question