Datastore Set Panel not working

local DataStoreService = game:GetService("DataStoreService")
local leaderstatsData = DataStoreService:GetDataStore("LeaderstatsData")

game.Players.PlayerAdded:Connect(function(player)
	
	local success, data = pcall(function()
		return leaderstatsData:GetAsync(player.UserId)
	end)
	
	if not success then print(`Failed to get data: {data}`) return end
	
	if not data then
		data = {
			emeralds = 0
		}
	end

	player:WaitForChild("leaderstats"):WaitForChild("emeralds").Value = data.emeralds

	player.leaderstats.emeralds.Changed:Connect(function(value)
		local NewData = {
			emeralds = value
		}
		if game:GetService("ReplicatedStorage"):WaitForChild("IsPrivateServer").Value == false then
			local success2, result = pcall(function()
				leaderstatsData:SetAsync(player.UserId, NewData)
			end)
			if not success2 then
				print(`Failed to save data: {result}`)
			end
		end
	end)
end)

and

script.Parent.set.OnServerEvent:Connect(function(plrInvoked, emeraldsSetAmount)
	local foundUserId = script.Parent.Parent.currentFoundUserId

	local dataToSave = {
		emeralds = tonumber(emeraldsSetAmount)
	}
	
	local leaderstatsData = game:GetService("DataStoreService"):GetDataStore("LeaderstatsData")
	
	local success, result = pcall(function()
		leaderstatsData:SetAsync(foundUserId.Value, dataToSave)
	end)
	
	if not success then
		print(`Failed to save data: {result}`)
	end
end)

try these scripts and let me know

1 Like

tysm! i used both of them, so what worked was the setting function, when i set my leaderstats datastore and rejoined it updated my leaderstats. but when my leaderstats change without using the set button, it doesn’t save. any ideas?

hold on, i enabled the wrong script and it worked, but im just addressing one bug with it rn

game.Players.PlayerRemoving:Connect(function(player)
	local NewData = {
		emeralds = player:FindFirstChild("leaderstats"):FindFirstChild("emeralds").Value
	}
	
	if NewData.emeralds == 0 or NewData.emeralds == nil then
		return -- not saving the data because it is 0 or not loaded yet.
	end
	
	local success, result = pcall(function()
		leaderstatsData:SetAsync(player.UserId, NewData)
	end)
	
	if not success then
		print(`Failed to save data: {result}`)
	end
end)

To save player’s data when they are leaving, you can use PlayerRemoving event. (add it to your first script)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.