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

How do I autosave data instead of saving only when a player leaves?

Asked by 8 years ago
Edited 8 years ago

So I have a script which saves player data whenever the player leaves. But I would want to make it so that it autosaves the data every few seconds. Because when a player leaves, I would be able to call on a function with the parameter of that specific player.

But if I were to make a loop, I will not be able to get each specific name of the players.

I have thought of making a 'LocalScript' which would be imported into every player when they join. And then I would be able to use game.Players.LocalPlayer to get the specific player. But I want to see if there are other methods of doing this.

My original script is here:

01local DSService = game:GetService("DataStoreService"):GetDataStore("DataSaving832723579985723")
02 
03game.Players.PlayerAdded:connect(function(player)
04    local playerId = "ID-"..player.userId
05 
06    local leaderstats = Instance.new("IntValue", player)
07    leaderstats.Name = "leaderstats"
08 
09    local money = Instance.new("IntValue", leaderstats)
10    money.Name = "Money"
11    money.Value = 0
12 
13    local exp = Instance.new("IntValue", leaderstats)
14    exp.Name = "Experience"
15    exp.Value = 0
View all 42 lines...

I hope someone can give me another idea for this.

1 answer

Log in to vote
1
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago
Edited 8 years ago

Datastores can only be used in ServerScripts so LocalScripts are out of the question (unless you want to use remote events, but I suggest against that in this case).

As for loops, this is the only way to repeated calls infinitely (as you can only recurse so deep before you hit a stack overflow), so we will have to use some sort of looping structure. I suggest have a while loop that repeats every x amount of time in which you loop through all the players in the game and save their data.

1while wait(5) do
2    for _, player in ipairs(game.Players:GetPlayers()) do
3        datastore:SetAsync("ID-"..player.userId, {
4            player.leaderstats.Money.Value,
5            player.leaderstats.Experience.Value,
6            player.leaderstats.Level.Value
7        })
8    end
9end
Ad

Answer this question