As DetectiveRaie said, you should use :InputBegan() to simply detect user input. Also remember UIS only works in 'LocalScript' not 'ServerScript' ( RECOMMENDED ONE )
Basic Code:
1 | local UserInputService = game:GetService( "UserInputService" ) |
2 | local requiredKey = Enum.KeyCode.E |
4 | UserInputService.InputBegan:Connect( function (key, gameProcessed) |
5 | if key.KeyCode = = requiredKey then |
Next, you will need to use remote function/event since it's client sided code if you want your attacks or stuff to be seen by all players/clients ( server )
Another way of doing it by using :GetPressedKeys() ( LESS RECOMMENDED )
Your code is actually fine and correct but there is something that makes it not work.
- You probably used ServerScript instead of LocalScript
- In line 8 of your code there's a local function named forceField and your attacks code is inside it.
- You forgot to call the function above
- If you want it to be seen by the server, you must use remote event.
Before getting into the code. There' 2 ways I usually use to detect input with :GetPressedKeys(), which are UserInputService.JumpRequest and Humanoid.Running or simply just use white loop
Basic Code: ( White Loop Usage )
01 | local UserInputService = game:GetService( "UserInputService" ) |
02 | local requiredKey = Enum.KeyCode.R |
04 | local function getPressedKey() |
05 | local pressedKey = UserInputService:GetKeysPressed() |
07 | for _, key in pairs (pressedKey) do |
08 | if key.KeyCode = = requiredKey then |
09 | print ( "Pressed: " , key.KeyCode) |
REMINDER: ALL stuff you want to do needs to be done on the server by using remotes
FYI: You can use remote function instead of remote event to make a built in cooldown for this