Is there a better way to make an automatic gun than using a while true do loop?

Hey! I’m working on a simple automatic gun and I was wondering if there is a better way than using a while true do loop to make it work. Is ther a way to do this? Any help would be very appreciated! :smile:
current client script:

workspace:WaitForChild(game.Players.LocalPlayer.Name)
local plr = game.Players.LocalPlayer
local char = plr.Character
local tool = script.Parent
while true do
	wait(0.1)
	if tool.Parent.Parent == char then
		-- fire the weapon
	end
end
5 Likes

Possibly use coroutines so you can yield the loop when the player stops firing? Although I don’t use coroutines often so I can’t help you with anymore more then a suggestion.

But maybe try looking into it?

2 Likes

I didn’t really know how to use coroutines so I tried “repeat until” and it seemed to work. Thanks for your help! :wink:
Here is the script I used:

tool.Equipped:Connect(function()
   equip()
   
   --//Automatic fire
   mouse.Button1Up:Connect(function()
   	mouseDown = false
   end)
   
   tool.Activated:Connect(function()
   	mouseDown = true
   	repeat
   		wait(0.01)
   		fire()
   	until not mouseDown
   end)
end)
5 Likes

Alrighty then, if you have any more problems with the automatic gun I’ll try my best to help here :slight_smile:

3 Likes

There actually is a better way. It’s called use the condition correctly.

while mouseDown do
    fire()
    wait()
end

Don’t yield at the start of an iteration, regardless of what loop you’re using, that’s bad practice. Use the condition to determine when the loop should terminate or not. Only if you need a non-terminating loop should you use true as a condition.

I don’t really like repeat in terms of a gun. Feels like my freedom is being taken for handling iterations and it just generally feels improper.

14 Likes