I want to create a magic attack that when you hold a key, you charge it up. However, i'm not sure how to do this using UserInputService...
I've tryed using if statements but that didn't work.
local UIS = game:GetService("UserInputService") UIS.InputBegan:Connect(function(input, typing) if typing then return end if input.KeyCode == Enum.KeyCode.R then if input.KeyCode == Enum.KeyCode.R then
Use the .InputEnded event to detect when they let the key off:
local uis = game:GetService("UserInputService") local holding uis.InputBegan:Connect(function(key,gpe) if gpe then return end if key.KeyCode == Enum.KeyCode.R then -- started holding -- you could do other stuff here holding = true end while holding and wait() do -- inside event or else if wont detect holding has been changed -- this will run when holding is true and every 0.033 seconds, you can change that of course end end) uis.InputEnded:Connect(function(key,gpe) if gpe then return end if key.KeyCode == Enum.KeyCode.R then -- the key is not being hold anymore -- you could do other stuff here holding = false end end)
Hope this helped!
I'd like to build off of what zamd suggested. In general, I agree with his usage of InputEnded
, however, I'd even suggest using an actual BoolValue
instance in your game to determine the value of holding
. This way, you can run .Changed
on it! I use this method a lot for issues like yours. Here's an example.
local UIS = game:GetService("UserInputService") local Players = game:GetService("Players") local Player = Players.LocalPlayer local IsHolding = Instance.new("BoolValue") IsHolding.Name = "IsHolding" IsHolding.Parent = Player UIS.InputBegan:Connect(function(key) if key.KeyCode == Enum.KeyCode.R then IsHolding.Value = true end end) UIS.InputEnded:Connect(function(key) if key.KeyCode == Enum.KeyCode.R then IsHolding.Value = false end end) IsHolding.Changed:Connect(function() if IsHolding.Value == true then --do action else --stop action end end)