I made a script to shoot a gun in a very simple way, being automatic for my M4A1 and a upcoming project however when not holding mouse1 it keeps shooting. Here is my code:
local mouse = game.Players.LocalPlayer:GetMouse() -- mouse varible script.Parent.Activated:Connect(function() --connects the function wait(0.1) -- the wait time between each shot while true do -- my way of looping it wait(0.08) script.Parent.Fire:FireServer(mouse.Hit.Position) --fires to server wait(0.08) end wait(0.1) end)
I'm only showing the local script since that is what checks to see if mouse1 is down. I think its beacuse of "while true do" and I know there are many better ways of looping but I have no idea how to do them. Does "while true do" mean while the script is TRUE (enabled) or the function is happening? I tried a few things:
I changed "while true do" to "while mouse.button1down == true do"
I added :
while true do if mouse.button1down then --Rest of the code
but for some reason while trying nr. 2. i got this error: "Expected identifer got ")"" And with nr. 1. it didn't shoot at all. Thanks.
This assumes you have basic knowledge of UserInputService
Use a variable.
In a local script,
local userInputService = game:GetService("UserInputService") local mouseDown = false -- Detect when mouse button 1 is pressed userInputService.InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then mouseDown = true end end) -- And the inverse userInputService.InputEnded:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then mouseDown = false end end)
Then you may use your while loop like this
while mouseDown == true do -- fire gun task.wait(0.06) -- Better version of wait(). Should be used in place of wait() in all cases. end
I would, however, also make a cooldown for your gun. In its current state, if you keep pressing the mouse and holding it down, it will spawn multiple while do loops and shoot at an undesired rate.
To circumvent,
local cooldown = false script.Parent.Activated:Connect(function() if cooldown == true then return end cooldown = true task.spawn(function() -- A new thread is necessary since the while loop will yield until the mouse button is released. task.wait(0.08) cooldown = false end) while mouseDown == true do -- fire gun task.wait(0.08) end end)
I've made many gun systems before and these are the tactics I use. I wrote all of this here on the website so if there's any errors, just reply and I'll fix them.