Answered by
4 years ago Edited 4 years ago
I suggest you use UserInputService
since ContextActionService
fires on InputBegan
and InputEnded
. That means that the function KeyPressed
will be called two times; once when you press the key, and once when you release the key.
I also made a setDebounce
function to reduce the boilerplate code. This should work exactly as you've inteded it to work.
The variable Pressed
was also unnecessary. You only need one if statement with one Debounce
variable.
You were setting the debounce variable inside the first if statement, but when the 5 seconds wait was over the compiler would go line to line and execute the next if statement in the same function call. Using 1 if statement fixed this problem.
2 | humanoid:EquipTool(sword) |
5 | humanoid:UnequipTools(sword) |
Here is the complete script.
02 | local replicatedStorage = game:GetService( "ReplicatedStorage" ) |
03 | local playersService = game:GetService( "Players" ) |
04 | local userInputService = game:GetService( "UserInputService" ) |
07 | local player = playersService.LocalPlayer |
08 | local character = player.Character |
09 | local humanoid = character:WaitForChild( "Humanoid" ) |
11 | local sword = replicatedStorage:FindFirstChild( "Sword" ) |
15 | local function setDebounce() |
21 | userInputService.InputBegan:Connect( function (input) |
22 | if input.KeyCode = = Enum.KeyCode.Z then |
24 | humanoid:EquipTool(sword) |
27 | humanoid:UnequipTools(sword) |
Please feel free to ask any questions you might have about my solution, and how I came up with it.