So I made an upgrade button and when you click it it fires an event, but I also want it to click really fast after holding for one second. This is my script:
local replicatedStorage = game:GetService("ReplicatedStorage")
local upgradeEvent = replicatedStorage:WaitForChild("RemoteEvents"):WaitForChild("UpgradeRemoteEvent")
local upgrade = "LuckUpgrade"
local upgradeButton = script.Parent
upgradeButton.MouseButton1Up:Connect(function()
upgradeEvent:FireServer(upgrade)
end)
There is also a ButtonDown … between the two you can tell they are holding it.
--keys
local player = game.Players.LocalPlayer
local userInputService = game:GetService("UserInputService")
local keyToCheck = Enum.KeyCode.Space
if userInputService:IsKeyDown(keyToCheck) then
print("Space key is currently held down")
elseif userInputService:IsKeyUp(keyToCheck) then
print("Space key is currently up")
end
--mouse
local player = game.Players.LocalPlayer
local userInputService = game:GetService("UserInputService")
local mouseButtonToCheck = Enum.UserInputType.MouseButton1button
if userInputService:IsMouseButtonPressed(mouseButtonToCheck) then
print("Mouse button is currently held down")
elseif userInputService:IsMouseButtonReleased(mouseButtonToCheck) then
print("Mouse button is currently released")
end
You can make use of MouseButton1Down (which detects when the player holds down their mouse) like this:
upgradeButton.MouseButton1Down:Connect(function()
local isHeldDown = false
upgradeButton.MouseButton1Up:Once(function()
-- Once disconnects the function after one time to prevent memory leaks
upgradeEvent:FireServer(upgrade)
isHeldDown = false -- no longer held down
end)
task.wait(1)
if isHeldDown == false then return end -- stop if player stopped holding
while isHeldDown == true do
-- spam the event here
end
end)
The reason why I put MouseButton1Up into the MouseButton1Down function is to prevent the code from running when the player clicks and holds their mouse again within the 1 second time frame, causing multiple runs
For the post above: the 1 second wait is the problem so it might not fit in this problem (I may be wrong though)
Your solution will lead to being locked in an endless loop … Try this.
local db=true
local isHeldDown = false
upgradeButton.MouseButton1Down:Connect(function()
if db then db = false
isHeldDown = true
while isHeldDown == true do task.wait(0.33)
if isHeldDown == false then db=true
break
end
end
end
end)
upgradeButton.MouseButton1Up:Once(function()
upgradeEvent:FireServer(upgrade)
isHeldDown = false
end)
Also it seems in this case you really don’t even need the down part just the up …