Values duplicating Data Save (Again)

(I asked this question 1 week before and I thought I fixed it, but I only tested it 1-2 times and went for 1 week break and then realized the values still duplicated sometimes and the thread was too old to go back, my fault sorry) Ok, so I wanted all things in a folder to save, it works but the values sometimes duplicate, I tried to debug it multiply times, but it didn’t work, it might be that it saves everything double, 1 in playeremoving and one in game:BindToClose() but without the game:BindToClose() it also somehow duplicated and I really don’t know how to fix it.

Code Here:

local DTS = game:GetService("DataStoreService")
local TycoonSave = DTS:GetDataStore("TycoonSave")
local ThingsToSaveTable = {}


game.Players.PlayerAdded:Connect(function(plr)
	
	
	
	
	local SaveTycoon = Instance.new("Folder")
	SaveTycoon.Parent = plr
	SaveTycoon.Name = "SaveTycoon"
	
	local Key = "Key_"..plr.UserId
	local Data
	

	local success, errormessage = pcall(function()
		Data = TycoonSave:GetAsync(Key)
	end)
	if success then
		if Data ~= nil then
			for i = 1, #Data do
				local temp = Instance.new("StringValue")
				temp.Parent = plr:WaitForChild("SaveTycoon")
				temp.Name = Data[i]
				temp.Value = Data[i]
			end
		end
	else
			print(errormessage)
	end
end)








game.Players.PlayerRemoving:Connect(function(plr)
	local Key = "Key_"..plr.UserId
	local Data
	for i, v in pairs(plr:WaitForChild("SaveTycoon"):GetChildren()) do
		if v:IsA("StringValue") then
				table.insert(ThingsToSaveTable, v.Value)
		end
	end
	
	local success, errormessage = pcall(function()
		Data = TycoonSave:SetAsync(Key, ThingsToSaveTable)
	end)
	if success then
		-- do nothing
	else
			print(errormessage)
	end
end)



game:BindToClose(function()
	local PlayersLeft = game.Players:GetPlayers()
	for i, plr in pairs(PlayersLeft) do
	local Key = "Key_"..plr.UserId
	local Data
	for i, v in pairs(plr:WaitForChild("SaveTycoon"):GetChildren()) do
		if v:IsA("StringValue") then
				table.insert(ThingsToSaveTable, v.Value)
		end
	end
	
	local success, errormessage = pcall(function()
		Data = TycoonSave:SetAsync(Key, ThingsToSaveTable)
	end)
	if success then
		-- do nothing
	else
			print(errormessage)
	end
	end
	end)
1 Like