Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How Can I Detect If Character Is Equipping A Tool?

This is my attempt.

plr = game.Players.LocalPlayer

repeat wait() until plr.Character

for _,v in pairs(plr.Character:GetChildren()) do
if v:IsA("Tool") then

end
end

while wait(1) do
if v then
v:Destroy()
end 
end

Why can't v be detected outside of the for loop?

2 answers

✓ Accepted answer

You're finding the tool, but you're not doing anything with it. The while loop doesn't know what the variable v is, because it is defined locally in the for loop. Just use the code in the for loop instead.

plr = game.Players.LocalPlayer

repeat wait() until plr.Character

for _,v in pairs(plr.Character:GetChildren()) do
    if v:IsA("Tool") then
        v:Destroy()
    end
end

If you do want to find v outside of the loop, then you only need to make a variable for it.

plr = game.Players.LocalPlayer
local tool;

repeat wait() until plr.Character

for _,v in pairs(plr.Character:GetChildren()) do
if v:IsA("Tool") then
tool = v
end
end

while wait(1) do
if tool then
v:Destroy()
end 
end

the variable v can't be detected outside of the loop because v is a local variable inside the for loop. You would have to define a global or local value before and change its content like this:

plr = game.Players.LocalPlayer
tool = nil
repeat wait() until plr.Character

for _,v in pairs(plr.Character:GetChildren()) do
if v:IsA("Tool") then
	tool  = v
end
end

while wait(1) do
if tool then
tool:Destroy()
end 
end

Also I'd propose to you to make the while loop a coroutine to not catch the script in it.

This discussion is preserved as it was. New answers, comments, and votes are closed.