UserInputService Hold Button

  1. What do you want to achieve?
    I want to make it so that if I click and hold “Z” on the keyboard, it will loop animation and particles until I stop holding, then it will shoot, like in the game “King Legacy” and other games.

  1. What is the issue?
    I don’t know how to make a hold event.
local Prompt = workspace.ProximityPrompt
local PromptService = game:GetService("ProximityPromptService")
local Holding = false 

PromptService.PromptButtonHoldBegan:Connect(function(HeldPrompt, Caller)
    if (HeldPrompt == Prompt) then 
       Holding = true 
       
       while (Holding == true) do 
           print("Prompt is being held by "..Caller.Name)
           task.wait(0.33)
       end
        print(Caller.Name.." stopped holding the prompt.")
    end
end)

PromptService.PromptButtonHoldEnded:Connect(function(HeldPrompt, Caller)
    if (HeldPrompt == Prompt) then 
        Holding = false
    end
end)

I said UserInputService not proximity prompt

UserInputService.InputBegan:connect(function(input)
		if input.KeyCode == Enum.KeyCode.Z then
	end
end)

like this but a hold event

local uis = game:GetService("UserInputService")

-- method 1

local holding = false

uis.InputBegan:connect(function(input, processed)
    if not processed then
        if input.KeyCode == Enum.KeyCode.Z then
            holding = true

           while holding do
               task.wait()
           end
        end
    end
end)

uis.InputEnded:connect(function(input)
    if input.KeyCode == Enum.KeyCode.Z then
        holding = false
    end
end)

-- method 2

uis.InputBegan:connect(function(input, processed)
    if not processed then
        if input.KeyCode == Enum.KeyCode.Z then
           while uis:IsKeyDown(input.KeyCode) do
               task.wait()
           end
        end
    end
end)
3 Likes

Method 2 works for me, but why does it print “held” 100+ times? That will bug the game if it keeps on spamming Anim:Play() I want it to just check if the player is holding once!

UserInputService.InputBegan:connect(function(input, Processed)
	if not Processed then
		if input.KeyCode == Enum.KeyCode.Z then
			while UserInputService:IsKeyDown(input.KeyCode) do
				print("Held")
				task.wait()
			end
			print("Stop Held")
		end
	end
end)

its a loop to keep it from stopping the function, its spamming “Held” because its a loop and its looping the function print("Held").

if you want to put an anim either play it before you run the loop, or in the loop put

if not Anim.IsPlaying then
    Anim:Play()
end
2 Likes

Thanks This works!1!1!1!1!1!1!

btw, how could I make it so when “Z” is holding, the player will rotate with the mouse position so like he is aiming?

you’d either have to rotate the player using CFrames or putting an AlignOrientation/BodyGyro into the player’s rootpart and CFrame that to the mouse position

1 Like

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