I've created a function in a local gun script that fires a bullet. How can I use 'while true do' and the mouse to make the gun automatic? By continuously, I mean over and over again.
This will not be the exact script but, you should get the idea...
If this helped, please be sure to accept.
local Firing -- We just make a variable to be used. KeyDown:Connect(function() --When pressing down --//Firing Firing = true while Firing and wait() do -- The "wait()" is just so it does not error when running the code very fast. -- Here is where the bullet is made end end) KeyUp:Connect(function() --When you let go --//Firing Firing = false -- We set Firing to false b/c, in KeyDown, the loop only runs if it is true end)
There are a few ways to do this. I'll suggest one:
The :Connect()
function on events actually returns an object of type RBXScriptConnection
, which itself has a method called :Disconnect()
. What this means is you can connect a function to an event and then disconnect it manually later on.
The event that you'd be interested in for continuous checking is RunService.Heartbeat
, which fires once per frame. When you detect a click down, connect your continuously updating function to the Heartbeat
event and save the connection reference in a variable. When the click ends, call :Disconnect()
on the saved connection and it will stop firing.
You can also use coroutines, concerning which there is some introductory material in the online book Programming in Lua.
Edit: FiredDusk's solution also works, but in general you should be very careful with that setup. If you ever want to trigger the firing function from somewhere else in the script, you must make sure to call it in a new thread. When an event fires, a connected function will automatically run in a new thread, but this is not the case if you just call the function directly, which might block the code which you call it from.