How can you make something function only if the player is holding down a key

I’m making a melee weapon and I only want the player to be able to attack when they’re holding right click.

I tried using UserInputService but it doesn’t work.

local UIS = game:GetService("UserInputService")
ready = false

UIS.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then
		ready = true
		print("ready TRUE")
	end
end)
UIS.InputEnded:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then
		ready = false
		print("ready TRUE")
	end
end)


		function on(t)
			local h = t.Parent:FindFirstChildOfClass("Humanoid")
		if h ~= nil and CanDmg == true and ready == true then
				CanDmg = false
				local cre = Creator.Value
				h:TakeDamage(parent.Dmg.Value)
				Handle.Swing:Stop()
				Handle.Hit:Play()
				
				if h.Health>0 then
					if not h:FindFirstChild("creator") then
						local ov = Instance.new("ObjectValue",h)
						ov.Name = "creator"
						ov.Value = game.Players:WaitForChild(cre.Name)
					else
						local ovs = h:GetChildren()
						
						for i = 1,#ovs do
							if (ovs[i].Name == "creator") then
								ovs[i].Value = game.Players:WaitForChild(cre.Name) end
						end
					end
				end
	
			
			end
		end	
	 
			
Handle.Touched:Connect(on)

I thought this would be simple to fix but I’m having a hard time figuring out what is wrong.

1 Like
local canFunction

(detect input and enable the canFunction variable)
(detect input stopping and disable the canFunction variable)

when something runs:
if canFunction then
(do your stuff)
end

Didn’t wok it seems:

local UIS = game:GetService("UserInputService")

local canFunction

UIS.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then
		canFunction = true
		print("TRUE")
	end
end)
UIS.InputEnded:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then
		canFunction = false
		print("False")
	end
end)

if canFunction then
	function on(t)
		local h = t.Parent:FindFirstChildOfClass("Humanoid")
		if h ~= nil and CanDmg == true then
			CanDmg = false
			local cre = Creator.Value
			h:TakeDamage(parent.Dmg.Value)
			Handle.Swing:Stop()
			Handle.Hit:Play()

			if h.Health>0 then
				if not h:FindFirstChild("creator") then
					local ov = Instance.new("ObjectValue",h)
					ov.Name = "creator"
					ov.Value = game.Players:WaitForChild(cre.Name)
				else
					local ovs = h:GetChildren()

					for i = 1,#ovs do
						if (ovs[i].Name == "creator") then
							ovs[i].Value = game.Players:WaitForChild(cre.Name) end
					end
				end
			end


		end
	end	
end
	
			
Handle.Touched:Connect(on)

I just noticed that print(“TRUE”) and print("FALSE) are not showing up in the output so I think the inputs are not executing. Is there a different way to do this?

Use a preconditional loop such as the while