How can I make the handcuffs work smoother?

Hi! I’m currently making a handcuff script but I’m having a bit of trouble. When the player gets cuffed, sometimes releasing works on the first try and sometimes it doesn’t. I know it has something to do with how the player gets clicked, but I don’t know what to fix.
(If the player clicks an accessory, you cant uncuff, but if they click a body part, you can.)

tool.Equipped:Connect(function()
	uis.InputBegan:Connect(function(input)
		if input.KeyCode == Enum.KeyCode.R then
			if mouse.Target.Parent:FindFirstChild("Humanoid") then
				if detained == true then
					local releasedEvent = script.Parent.PlayerReleased
					releasedEvent:FireServer(mouse.Target.Parent:FindFirstChild("Humanoid"), mouse.Target.Parent.HumanoidRootPart)
					print(plr.Name.." has released a detainee")
					detained = false
				end
			else
				if mouse.Target.Parent.Parent:FindFirstChild("Humanoid") then
				if detained == true then
					local releasedEvent = script.Parent.PlayerReleased
					releasedEvent:FireServer(mouse.Target.Parent.Parent:FindFirstChild("Humanoid"), mouse.Target.Parent.Parent.HumanoidRootPart)
					print(plr.Name.." has released a detainee")
					detained = false
					end
				end
			end	
		end
	end)
end)

All help is greatly appreciated, thanks!

Try this:

tool.Equipped:Connect(function()
	uis.InputBegan:Connect(function(input)
		if input.KeyCode == Enum.KeyCode.R then
			if not mouse.Target:FindFirstAncestorOfClass("Model") then
				return
			end
			if mouse.Target:FindFirstAncestorOfClass("Model"):FindFirstChild("Humanoid") then
				if detained == true then
					local releasedEvent = script.Parent.PlayerReleased
					releasedEvent:FireServer(mouse.Target.Parent:FindFirstChild("Humanoid"), mouse.Target.Parent.HumanoidRootPart)
					print(plr.Name.." has released a detainee")
					detained = false
				end
			else
				if mouse.Target:FindFirstAncestorOfClass("Model"):FindFirstChild("Humanoid") then
				if detained == true then
					local releasedEvent = script.Parent.PlayerReleased
					releasedEvent:FireServer(mouse.Target.Parent.Parent:FindFirstChild("Humanoid"), mouse.Target.Parent.Parent.HumanoidRootPart)
					print(plr.Name.." has released a detainee")
					detained = false
					end
				end
			end	
		end
	end)
end)

The script didn’t work. Animation didn’t play and nothing printed

Weird. Does the original script still work? I’m not sure why the code wouldn’t work. If there’s errors what do you see? If not, try removing

if not mouse.Target:FindFirstAncestorOfClass("Model") then
	return
end