local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("Datastored")

local tries = 3
local dataLoaded = false


local function Set(plr)
	if dataLoaded then

		local key ="plr-" .. plr.UserId
		local count = 0

		local data = {
			["Clicks"] = plr.leaderstats.Click.Value,
			["Prestiges"] = plr.leaderstats.Prestiges.Value,
			["Coins"] = plr.leaderstats.Coins.Value,
			["Class"] = plr.leaderstats.Class.Value
		}

		local success, err

		repeat
			success, err = pcall(function()
				dataStore:SetAsync(key, data)
			end)

			count = count + 1
		until count >= tries or success

		if not success then 
			warn("Failed to set data. Error code: " .. tostring(err))
			return
		end
	else
		return
	end
end


local function Get(plr)

	local key ="plr-" .. plr.UserId
	local count = 0

	local data

	local success, err


	repeat
		success, err = pcall(function()
			data = dataStore:GetAsync(key)
		end)

		count = count + 1
	until count >= tries or  success

	if not success then 
		warn("Failed to read data. Error code: " .. tostring(err))

		plr:Kick("You have been kicked to save your data. Please Rejoin")

		return 
	end

	if success then 
		if data then 
			return data
		else
			return {
				["Clicks"] = 0,
				["Prestiges"] = 0,
				["Coins"] = 0,
				["Class"] = 0
			}
		end
	end
end

local function createLeaderstats(plr)
	local values = Get(plr)

	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr 

	local Clicks = Instance.new("IntValue")
	Clicks.Name = "Clicks"
	Clicks.Parent = leaderstats

	local Prestiges = Instance.new("IntValue")
	Prestiges.Name = "Prestiges"
	Prestiges.Parent = leaderstats
	
	local Coins = Instance.new("IntValue")
	Coins.Name = "Coins"
	Coins.Parent = leaderstats
	
	local Class = Instance.new("IntValue")
	Class.Name = "Class"
	Class.Parent = leaderstats

	Clicks.Value = values.Clicks
	Prestiges.Value = values.Prestiges
	Coins.Value = values.Coins
	Class.Value = values.Class

	dataLoaded = true
end

players.PlayerRemoving:Connect(Set)
players.PlayerAdded:Connect(createLeaderstats)

game:BindToClose(function()
	for i, v in next, game.Players:GetChildren() do
		if v then
			Set(v)
		end
	end
end)

2 comments

0

Be more specific with "its not working". What's not working? Are the values loading incorrectly, is it erroring, give more detail so we can identify the problem.

0

You showed no attempt for the community to answer your question. Not only that, you didn't even write the context of the problem meaning, you had to write a description. Is there any errors? Did you try using a print function? etc. For that your question will be closed.