How would I detect a double click correctly?

Hey, I am trying to make a double click for my sword so that if a player double clicks with their sword then they do a special attack!

The script I made is very choppy and sometimes doesn’t even detect a double click or gives the special attack when the player didn’t even double click.

Script:

local UserInputService = game:GetService("UserInputService")

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

local Click = 0

UserInputService.InputBegan:Connect(function(input,Processed)
	if not Processed and script.Parent.Parent == character then
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			local T1 = tick()
			
			local Reset = coroutine.create(function()
				if Click > 0 then
					wait(.5)
					Click = 0				
				end
			end)
			
			coroutine.resume(Reset)

			Click += 1

			local compare = tick() - T1
			
			if compare < .5 and Click >= 2 then
				script.Parent.Fire:FireServer(2)
			else
				script.Parent.Fire:FireServer(1)
			end
		end
	end
end)

Maybe you can try out what this post did?

This was made for GuiButtons in mind, but you can change the script around to work for what you were trying to do

They did use a wait which I recommend changing to the new task.wait

Here’s a ‘UserInputService’ implementation that detects ‘double’ clicks, porting it to a tool’s ‘Activated’ signal should be simple enough.

local Enumeration = Enum
local Game = game
local RunService = Game:GetService("RunService")
local UserInputService = Game:GetService("UserInputService")

local LastClickTime = 0
local DoubleClickTime = 0.15 --Maximum time in seconds for two consecutive clicks to be considered a 'double' click.

local function OnInputBegan(InputObject, GameProcessed)
	if GameProcessed then return end
	if InputObject.UserInputType ~= Enumeration.UserInputType.MouseButton1 then return end
	local CurrentClickTime = RunService.Stepped:Wait()
	if (CurrentClickTime - LastClickTime) < DoubleClickTime then
		print("Double click!")
	end
	LastClickTime = CurrentClickTime
end

UserInputService.InputBegan:Connect(OnInputBegan)
2 Likes

Sometimes it doesn’t work if you’re using a touchpad.

https://developer.roblox.com/en-us/api-reference/enum/UserInputType

I use a trackpad as well but mine has left mouse & right mouse buttons, I’m not sure what ‘UserInputType’ corresponds to trackpads that lack these buttons.

Yeah, I am talking about the touchpads that come with laptops.

You may want to increase the hard-coded 0.15 second time window.