Saving tools with DataStore2

Im trying to make a DataStore2 saving system, I made a script that works, but removes all tools and replaces them when updated.
I do not want the tools to be replaced, I want just the new tool to be added.

If I didnt replace the tools then the tools would duplicate themselves. (also I want the player to be able to get multiple of the same tool)
Also the duplicate tool doesnt save, but its still in the tools folder when tools get updated
How could I do that?

Code:

local DataStore2 = require(script.Parent.DataStore2)

local toolsName = "tools1"

DataStore2.Combine("DATA", "coins", toolsName)

local DEFAULT_TABLE = {}

game.Players.PlayerAdded:Connect(function(player)
	local tools = DataStore2(toolsName, player)

	local tool = script.Tools:Clone()
	tool.Parent = player

	local function toolUpdate(updatedTable)
		player.Tools:ClearAllChildren() -- if i didnt add this then the tools would duplicate themselves
		local MyTable = tools:GetTable(updatedTable)
		for key, value in pairs(MyTable) do
			local thing = Instance.new("NumberValue")
			thing.Name, thing.Value = key, value
			thing.Parent = player.Tools
		end
	end
	

	toolUpdate(tools:Get(DEFAULT_TABLE))
	
	tools:OnUpdate(toolUpdate)
end)

workspace.TOOL.ClickDetector.MouseClick:Connect(function(pName)
	local plr = game.Players:FindFirstChild(pName.Name)
	
	local newitem = tostring(math.random(1,1000000))
	local TableDataStore = DataStore2(toolsName, plr)
	local tablev = TableDataStore:GetTable(DEFAULT_TABLE)
	table.insert(tablev, newitem)
	TableDataStore:Set(tablev) 
	
end)
1 Like

So I noticed that I could just load the tools when entering the game, and add new tools to the tool folder manually, and leave the update function blank, but is that a good idea?

local DataStore2 = require(script.Parent.DataStore2)

local toolsName = "tools1.1"

DataStore2.Combine("DATA", "coins", toolsName)

local DEFAULT_TABLE = {}

game.Players.PlayerAdded:Connect(function(player)
	local tools = DataStore2(toolsName, player)

	local tool = script.Tools:Clone()
	tool.Parent = player
	
	local function toolUpdate(updatedTable)
		--player.Tools:ClearAllChildren()
		local MyTable = tools:GetTable(DEFAULT_TABLE)
		
		for key, value in pairs(MyTable) do
			local thing = Instance.new("StringValue")
			thing.Name = value
			thing.Parent = player.Tools
		end
	end
	
	toolUpdate(tools:Get(DEFAULT_TABLE))
end)

workspace.TOOL.ClickDetector.MouseClick:Connect(function(pName)
	local plr = game.Players:FindFirstChild(pName.Name)
	
	local tool = game.ReplicatedStorage.Tools:GetChildren()[math.random(1,#game.ReplicatedStorage.Tools:GetChildren())]
	local newitem = Instance.new("StringValue")
	newitem.Name = tool.Name
	newitem.Parent = plr.Tools
	
	local TableDataStore = DataStore2(toolsName, plr)
	local tablev = TableDataStore:GetTable(DEFAULT_TABLE)
	table.insert(tablev, newitem.Name)
	TableDataStore:Set(tablev) 
	
end)

wow thanks for the help everyone :confused:

figure it out in this topic