How to make the function repeat while player holding right click

This is kinda hard to explain so im gonna break it down but i have a script that activates when Mouse Button1 is down and i want it to repeat while it is still being held down, I’ve been stuck on this for about a day.

Here is the part of the script that i need help with.

function Fire()
if Ammuntion > 0 then
if mouse.Target ~= nil and mouse.Target.Parent:FindFirstChild(“Humanoid”) and Ammuntion > 0 then
Firing = true
while Firing == true and Ammuntion > 0 do
if mouse.Target then
if mouse.Target.Parent:FindFirstChild(“Humanoid”) then
Ammuntion -= 1
if Ammuntion > 0 then
game.ReplicatedStorage.Fire1:FireServer(mouse.Target)
end
end
end
task.wait(0.13)
end
elseif mouse.Target.Parent.Name ~= “Enemy” and mouse.Target ~= nil then
Firing = true
while Firing == true and Ammuntion > 0 and mouse.Target ~= nil do
Ammuntion -= 1
game.ReplicatedStorage.Miss1:FireServer(mouse.Hit.Position, mouse.Hit.Rotation)
task.wait(0.13)
end
end
end
end

mouse.Button1Down:Connect(Fire)

You can use the UserInputService

local UserInputService = game:GetService("UserInputService")

local function fire()
	-- Your code here
end

while true do
	if UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) then
		fire()
	end
	task.wait(1)
end
1 Like

does this work in a local script because im trying to run the code but it wont work?

The code fires every second because of task.wait(1)

I’ll edit it so it waits after instead of before

it might just not work with my script, I’ll edit my script and see if it works afterwards.

local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
local Button2Down = false
Mouse.Button2Down:Connect(function()
	Button2Down = true
	while Button2Down do
		-- code here
	end
end)
Mouse.Button2Up:Connect(function()
	Button2Down = false
end)
2 Likes

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