Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

DataStore not working?

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!

2 answers

✓ Accepted answer

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)

1 comment

0

My script's still don't work, any other errors you can see in them?

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.

3 comments

1

That won't really help :( I need it to save points, then load them, not add points. Also, isn't that exactly what the tutorial showed you how to do?? Add 50 points when they join? ..

0

It saves points, adds 50, player leaves, same player comesloads points, adds 50 again.

0

Yes it was the same concept, except the tutorial didnt give the whole script. If you copy and paste that into a script it wont work.. Just give the script a try it saves and loads points.

This discussion is preserved as it was. New answers, comments, and votes are closed.