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

Stop operation when tool is deselected?

Player = game.Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Parent = Player.Backpack
local mouse = Player:GetMouse()
tool.Name = "SOMETHING"
local tool2 = Instance.new("Part", tool)

tool2.Transparency = 1
tool2.Name = "Handle"

tool.Selected:connect(function()
	mouse.KeyDown:connect(function(key)
		if key == "z" then
			print("TESTING")
		end
	end)
end)


How do I make it so when I un-equip the tool and then I press Z, nothing will happen?

1 answer

✓ Accepted answer

Every tool has these functions:

  • Equipped ( mouse object )
  • Unequipped

So, I would recommend making a function that you can connect/disconnect whenever the player equips/unequipped the tool, E.G:

function printText()
	print("Player joined the game.)
end

local func = game.Players.PlayerAdded:connect(printText) -- does the function

func:disconnect() -- stops it from working again

So:

Player = game.Players.LocalPlayer
local tool = Instance.new("Tool")
tool.Parent = Player.Backpack
local mouse = Player:GetMouse()
tool.Name = "SOMETHING"
local tool2 = Instance.new("Part", tool)

tool2.Transparency = 1
tool2.Name = "Handle"

function attack(key)
	key = key:lower() -- very important, use this every time you check for a lowercase letter
	if key == "z" then -- use tab for formatting, not spaces
		print("TESTING")
	end
end

local func = mouse.KeyDown:connect(attack)

function equip() -- this is better
	func:connect()
end

function unequip()
	func:disconnect()
end

Hopefully this works. If not, just use a debounce.

2 comments

0

Thank you, but can you also demonstrate how to use a debounce? I've asked around and people said its complicated to explain.

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