Holding button for x amount of seconds

to explain what i want to do here:

  • theres a power button on a vehicle gui
  • the player needs to hold the power button down for X seconds before the vehicle starts
  • if the player let go of the power button it does nothing and re-randomizes how long the player have to press the button

currently have this

function set()
	while hold == true do
		task.wait(.2)
		if math.random(1,10) == 1 then
			state = true
			hold = false
			return
		else
			state = false
		end
	end
end

button.MouseButton1Down:Connect(function()
	hold = true
	set()
end)

button.MouseButton1Up:Connect(function()
	hold = false
end)

issues with this:

  • the player doesn’t actually have to hold the button down, it just does it with just a click
  • little control on how long the player have to hold down the button for

any help will be appreciated!

1 Like
local function startEngine()
	print("Engine Started!")
end

local engineThread, hold = nil, false
button.MouseButton1Down:Connect(function()
	if hold then return end
	hold = true
	engineThread = task.delay(math.random(1, 10), startEngine)
end)

button.MouseButton1Up:Connect(function()
	if not hold then return end
	hold = false
	if engineThread then 
		task.cancel(engineThread) 
		engineThread = nil
	end
end)
1 Like
local holdStartTime = nil -- Variable to store button press time

button.MouseButton1Down:Connect(function()
  holdStartTime = tick() -- Record time when button is pressed
  hold = true
end)

button.MouseButton1Up:Connect(function()
  hold = false
  if holdStartTime then -- Check if button was previously pressed
    local holdTime = tick() - holdStartTime -- Calculate hold duration
    -- Replace 3 with your desired hold duration in seconds
    if holdTime >= 3 then
      state = true -- Set state to true if held long enough
    end
    holdStartTime = nil -- Reset hold start time
  end
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.