Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago
Edited 7 years ago

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

Log in to vote
0
Answered by
FiredDusk 1466 Moderation Voter
7 years ago

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)
0
It says KeyDown & KeyUp are not identified. alonzo12345 60 — 7y
0
"This will not be the exact script but, you should get the idea". <------------ FiredDusk 1466 — 7y
0
So, of course it will no work... FiredDusk 1466 — 7y
0
If you need help, contact me on roblox: FiredDusk FiredDusk 1466 — 7y
Ad
Log in to vote
1
Answered by
duckwit 1404 Moderation Voter
7 years ago
Edited 7 years ago

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.

Answer this question