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 Disable a Tool for a user when they Unequipped the Tool?

I very well know the Unequipped Event and i know how to use it. Although once i added the Unequipped Event to the script, when ever I would Equip it once again it wouldn't work. Why?(This is FE)

--Local script--
repeat wait() until game.Players.LocalPlayer.Character
Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()
en = true

script.Parent.Equipped:Connect(function()
	script.Disabled = false
	Mouse.KeyDown:Connect(function(Key)
		if Key == "r" then
			if not en then return end
			en = false
			script.Parent.RemoteEvents:FireServer()
			wait(0.5)
			en = true
		end
	end)
end)

script.Parent.Unequipped:Connect(function()
	script.Disabled = true
end)
--Server script--
script.Parent.RemoteEvents.OnServerEvent:Connect(function()
	local Part = Instance.new("Part")
	Part.Parent = game.Workspace
	Part.CFrame = game.Players.LocalPlayer.Character.Head.CFrame * CFrame.new(0,0,-5)
	Part.BrickColor = BrickColor.new("Really black")
end)

1 answer

✓ Accepted answer

Don't disable the entire script. If you disable it, it won't run anymore so you can't re-enable it from inside the same script. Instead of disabling it, use a variable that determines whether the tool can be used or not and change the variable accordingly.

Also, don't connect Mouse.KeyDown everytime the player equips the tool. First of all, KeyDown is deprecated. Use InputBegan for UserInputService instead, or ContextActionService's BindAction when dealing with inputs. Secondly, you will have tons of connections if the player equips and unequips the tool.

--Local script--
Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()
en = true

local toolEquipped = false
local UserInputService = game:GetService("UserInputService")

script.Parent.Equipped:Connect(function()
	toolEquipped = true
end)

script.Parent.Unequipped:Connect(function()
    toolEquipped = false
end)

UserInputService.InputBegan:Connect(function(input, gp)
	if gp then return end
	if not toolEquipped then return end -- do not run if the tool is not enabled!
	if input.KeyCode = Enum.KeyCode.R then
		if not en then return end
		en = false
		script.Parent.RemoteEvents:FireServer()
		wait(0.5)
		en = true
	end
end)

I used toolEquipped to determine if the code should run when pressing r.

Hope this helps! :)

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