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

Why isn't my data store script working?

So I'm trying to use Data Store to store to stats, but for some reason, the too stats are always the same when they load. In game though, they will be changed normaly. But upon joining a game, both the stats are set to the same value. Here is my script:

local ds = game:GetService("DataStoreService"):GetDataStore("mySecretKey") --not my actual thinger

game.Players.PlayerAdded:connect(function(plr)
	plr:WaitForDataReady() -- make sure we aren't looking for leaderstats before they are created
	local uk = ("ithatofd"..plr.userId)
	local stats = plr:FindFirstChild("leaderstats"):GetChildren()
	for i=1, #stats do
		stats[i].Value = ds:GetAsync(uk)
	end
end)

game.Players.PlayerRemoving:connect(function(plr)
	plr:WaitForDataReady() -- make sure we aren't looking for leaderstats before they are created
	local uk = ("ithatofd"..plr.userId)
	local stats2 = plr:FindFirstChild("leaderstats"):GetChildren()
	for i=1, #stats2 do
		ds:SetAsync(uk, stats2[i].Value)
	end
end)

Is there a reason to this?

2 answers

✓ Accepted answer
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
local DS = DSS:GetDataStore("NAME OF YOUR DATA STORE")

function GetKey(Plr) -- So you can easily change the Key.
	return ("Player: "..Plr.UserId)
end

function SaveStats(Plr)
	Plr:WaitForDataReady()
	local Key = GetKey(Plr)
	local Stats = Plr:WaitForChild("leaderstats"):GetChildren()
	local Table = {}

	for i = 1, #Stats do
		table.insert(Table, i, Stats[i].Value)
	end
	
	DS:SetAsync(Key, Table)
end

Players.PlayerAdded:connect(function(Plr)
	Plr:WaitForDataReady()
	
	local Key = GetKey(Plr)
	local Stats = Plr:WaitForChild("leaderstats"):GetChildren()
	local HasValues = DS:GetAsync(Key)
	
	if HasValues then
		for i = 1, #Stats do
			Stats[i].Value = DS:GetAsync(Key)[i]
		end
	end
end)

Players.PlayerRemoving:connect(function(Plr)
	SaveStats(Plr)
end)

game.OnClose = function()
	for i, v in pairs(Players:GetPlayers()) do
		delay(0, function()
			SaveStats(v)
		end)
	end
end

I didn't check if it works, but I am pretty sure that this is your problem: stats[i].Value = ds:GetAsync(uk)

It should've been: stats[i].Value = ds:GetAsync(uk)[i]

Because you are telling the Script to get the first value of the table.

You are welcome ;)

~Manchester1002.

1 comment

0

yes! that works perfectly! thank you so much!

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