In this script when the player touches the part, it will destroy only object in specific in the backpack. The script works if I leave only " one if ", if I add " elseif ", it no longer works. What could I be doing wrong? and I need the script to check if the player has one of these tool and destroy it.
function hit(part)
if hit == nil then return end
local h = game.Players:GetPlayerFromCharacter(part.Parent)
part.Parent.Humanoid:UnequipTools()
if h ~= nil then
h.Backpack.diamond:Destroy()
elseif h ~= nil then
h.Backpack.golden:Destroy()
end
end
script.Parent.Touched:connect(hit)
function hit(hit) ---change this to hit
if hit == nil then return end
local h = game.Players:GetPlayerFromCharacter(part.Parent)
part.Parent.Humanoid:UnequipTools()
if h ~= nil then
h.Backpack.diamond:Destroy()
--else if should be remove
h.Backpack.golden:Destroy()
end
end
script.Parent.Touched:connect(hit)
it must work now and also dont add else if with the same stuff
If i leave like this, don’t get error, but if i add another tool in the script, get error.
says that the tool is not part of the backpack. At the very moment, it doesn’t. only if the player touches the part.
function hit(part)
if hit == nil then return end
local h = game.Players:GetPlayerFromCharacter(part.Parent)
part.Parent.Humanoid:UnequipTools()
if h ~= nil then
h.Backpack.diamond:Destroy()
end
end
script.Parent.Touched:connect(hit)
local toolnames = {
"diamond",
"golden"
}
function hit(hit) ---change this to hit
local h = game.Players:GetPlayerFromCharacter(part.Parent)
if not h then return end
part.Parent.Humanoid:UnequipTools()
for _,tool in pairs(h.Backpack:GetChildren()) do
if table.find(toolnames,tool.Name) then
tool:Destroy()
end
end
end
script.Parent.Touched:Connect(hit)
It puts all the names of the tools you want to destroy in a table, loops through the children in the backpack and if their name is equal to a thing in the table, destroy it
Your error is being caused because one of the tools is not found in the backpack, causing an issue where it tries to destroy something the doesn’t exist, causing an error