The most common way to detect input is using UserInputService
or ContextActionService
:
You would have your central activation function, which is just your code:
local toggle = false
local function AuraTrigger()
toggle = not toggle
if toggle then
AuraEvent:FireServer()
else -- this is pseudocode!
local Effect = -- find effect
Effect:Destroy()
end
end
We can then just call this function when we want the aura to be toggled.
UserInputService
has 3 events (InputBegan
, InputEnded
, and InputChanged
) you can listen to to figure out what action to take.
In this example, I look at the returned input object’s KeyCode
to find out whether I should call AuraTrigger
or not:
local UserInputService = game:GetService("UserInputService")
local function onInputBegan(input, gameProcessed)
if not gameProcessed then -- if Gui's are not overriding the input,
if input.KeyCode == Enum.KeyCode.F then -- if the key pressed is F,
AuraTrigger()
end
end
end
UserInputService.InputBegan:Connect(onInputBegan)
ContextActionService
uses the concepts of “actions” to run functions based on a specific key you pressed. You can bind these actions with ContextActionService:BindAction
and unbind them using ContextActionService:UnbindAction
.
In this example, I just binded an action named AuraToggle
to the F
keycode enum, and I read the returned state
enum to see if the player is pressing the key down:
local ContextActionService = game:GetService("ContextActionService")
local function onFPress(name, state, input)
if state == Enum.UserInputState.Begin then -- if the key is pressed
AuraTrigger()
end
end
ContextActionService:BindAction(
"AuraToggle",
onFPress,
false,
Enum.KeyCode.F -- you can fit more in here if you want
)