I have a script that loads the tools using data saving. The tools loading is fine but sometimes I get 2+ of the same tool. To counteract this, I wrote this: Why does it not work?
--I tried this in a local script in StarterPlayerScipts and in a playerAdded function on the server.
local player = game.Players.LocalPlayer
local backpack = player:WaitForChild("Backpack")
local contents = {}
for i, v in pairs(tools:GetChildren()) do
if not contents[v] then
table.insert(contents, v)
else
v:Destroy()
end
end
Likely because of the way you set up the system, the way you’re retrieving the tool from contents uses a dictionary look up (meaning it sees v as a key rather than a value in a table and tries ot see if it has a truthy value), but you have a table, use table.find(contents, v) instead of contents[v]
local player = game.Players.LocalPlayer
local backpack = player:WaitForChild("Backpack")
local contents = {}
for i, v in pairs(tools:GetChildren()) do
if not table.find(contents, v) then
table.insert(contents, v)
else
v:Destroy()
end
end
What is tools? did you mean to get the children of the backpack? Also, this wont work if the tools are added before the script has a chance to destroy them. Also, I think it would work better if this was server sided (although I’m not sure if they work in StarterPlayerScripts).
I think it’s best you check out the way the tools are even being added to their backpack, maybe it’s sometihng wrong there that it’s allowing duplicates
How exactly are you putting the tools into the player’s backpack? May I see the code responsible for that?
I think it would be best if you get all the tools and put them into a table, go through that table checking for duplicates (you’d have to compare a property such as the Name since no 2 instances will ever be the same, which is likely why the table.find method didn’t work either) and then put them into their backpack
You are adding an instance to the table. Because each instance of the tool is different, it will do nothing. Use this instead:
local player = game.Players.LocalPlayer
local backpack = player:WaitForChild("Backpack")
local contents = {}
for i, v in pairs(tools:GetChildren()) do
if not table.find(contents, v.Name) then
table.insert(contents, v.Name)
else
v:Destroy()
end
end