Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make a function play continuously while the mouse is down?

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.

2 answers

✓ Accepted answer

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)

4 comments

0

It says KeyDown & KeyUp are not identified.

0

"This will not be the exact script but, you should get the idea". <------------

0

So, of course it will no work...

0

If you need help, contact me on roblox: FiredDusk

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.