Struggling to make a hold button GUI

This script is a mess and I don’t know what else I can do to make a simple GUI button that can hold at least 5 seconds to end the player. What and how is the simplest most efficient way to do this better than my scripting?

local Button = script.Parent.Bleed
local MouseBeingHeldDown = false
local tt = 0

Button.MouseButton1Down:Connect(function()
	MouseBeingHeldDown = true	
	while MouseBeingHeldDown == true do
		print("Mouse is being held down.")
		wait(1)
		tt = tt + 1
		print(tt)
		if MouseBeingHeldDown == false then print("returned!") return
		elseif tt >= 5 and MouseBeingHeldDown == true then
			game.Players.LocalPlayer.Character.Humanoid.Health = 0
		end
		--if tt == 5 then
		--	print(tt)
		--	game.Players.LocalPlayer.Character.Humanoid.Health = 0
		--else
		--	print(tt)
		--end
	end
end)

Button.MouseButton1Up:Connect(function()
	MouseBeingHeldDown = false
	tt = 0
end)

This is what I came up with. I used RunService.RenderStepped and tick().

local Kill_Button : TextButton = nil -- Change nil to path of button
local Kill_Connection

local Run_Service = game:GetService("RunService")
local Players = game:GetService("Players")

local LocalPlayer = Players.LocalPlayer
local Character = LocalPlayer.Character

if not Character then
	repeat
		task.wait()
	until LocalPlayer.Character ~= nil
	Character = LocalPlayer.Character
end

local Humanoid = Character:FindFirstChild("Humanoid") or Character:WaitForChild("Humanoid")

Kill_Button.MouseButton1Down:Connect(function()
	if Humanoid.Health ~= 0 then
		local Target_Time = tick() + 5

		Kill_Connection = Run_Service.RenderStepped:Connect(function()
			Kill_Button.Text = tostring(math.ceil(Target_Time - tick()))
			if tick() > Target_Time then
				Humanoid.Health = 0
				Kill_Button.Text = "haha dead"
				Kill_Connection:Disconnect()
			end
		end)
	end
end)

local function Reset()
	if Humanoid.Health ~= 0 then
		Kill_Button.Text = "die"
		if Kill_Connection then
			Kill_Connection:Disconnect()
		end
	end
end

Kill_Button.MouseButton1Up:Connect(Reset)

Kill_Button.MouseLeave:Connect(Reset)
1 Like

Thanks! Didn’t expect this kind of scripting just for a simple hold button.

1 Like