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

How to make tool only usable while equipped?

Right now I have made a gun tool. The only problem is that when I use any of the controls while it isn't equipped (like left clicking) it activates the gun. I tried to disable all of the scripts in the gun but it did not work.

1 answer

✓ Accepted answer

There are 2 events, Tool.Equipped and Tool.Unequipped, from name you can tell when they both fire, you can create variable called isEquipped, in Tool.Equipped set the variable to true and in Tool.Unequipped to false, in .Activated check if isEquipped is true before firing, this method is noob though, here is small code example:

local isEquipped = false

Tool.Activated:Connect(function()
	if not isEquipped then
		return -- Return will stop the function so it won't continue
	end

	print("Tool activated while equipped")
end)

Tool.Equipped:Connect(function()
	isEquipped = true
end)

Tool.Unequipped:Connect(function()
	isEquipped = false
end)

The better method is pro method, when you do Tool.Activated:Connect you are creating a connection, every time the event fires the connection is going to execute the connected function, you can disconnect this connection, this will stop it from executing the function, this is done using :Disconnect, every time user equips the tool you are going to connect the function as usual, but when he unequipps you are going to disconnect the connection:

-- We need to create variable here since "Unequipped" connection
-- needs to have access to the variable too
local activatedConnection

local function onToolActivated()
	print("Tool activated while equipped")
end

Tool.Equipped:Connect(function()
	-- ":Connect" returns the newly created connection
 	activatedConnection = Tool.Activated:Connect(onToolActivated)
end)

Tool.Unequipped:Connect(function()
	activatedConnection:Disconnect()
end)

1 comment

0

That worked thanks

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