I'm trying to use DataStore, I have two scripts, a saving and a loading script, inside ServerScriptService. I'm trying to save points, put there by an edited LinkedLeaderboard script, when the game closes, then the other script is just supposed to load them when they come back. Here's the saving script:
game.OnClose = function() for i,v in pairs(game.Players:GetPlayers()) do local ds = game:GetService("DataStoreService"):GetDataStore("savepoints") local key = "user_"..v.userId ds:UpdateAsync(key, function(oldValue) local newValue = oldValue or 0 newValue = v.leaderstats.Points return newValue end) end wait(5) end
And the loading script:
game.Players.PlayerAdded:connect(function(p) local ds = game:GetService("DataStoreService"):GetDataStore("savepoints") local loadpoints = ds:GetAsync("user_"..p.userId) p.leaderstats.Points = loadpoints end)
I'm getting the error leaderstats isn't a valid member of player, when it should be since it's put there by the linked leaderboard. I don't know if this is the only error, could you help me out? I just learned how to use datastore today, so I don't think I got it all right.
Thanks!
You don't know immediately which script will run first - the leaderboard scsript, or your data store script. If the data store script runs first, it will cause an error because you are assuming that "leaderstats" was created. Instead, you need to wait until it is added.
game.Players.PlayerAdded:connect(function(p) local ds = game:GetService("DataStoreService"):GetDataStore("savepoints") local loadpoints = ds:GetAsync("user_"..p.userId) --wait until the leaderstats object is added while not p:FindFirstChild("leaderstats") do p.ChildAdded:wait() end p.leaderstats.Points = loadpoints end)
I know this might not help with your answer but I do have a script in my models called "datastore leaderboard", it adds 50 points everytime a player joins. Try it out :), should help out with your understanding. Also try using the :OnUpdate() method.