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

Why does my script unequip the tool even though i havent pressed the key twice?

Asked by
Dec_ade 47
4 years ago
Edited 4 years ago

The sword automatically unequips itself after the debounce has ended

The local script

01local Pressed = false
02local Debounce = false
03 
04local function PressedKey()
05if Pressed == false and Debounce == false then 
06    print("KeyPressed")
07    Pressed = true
08    Humanoid:EquipTool(Sword)
09    Debounce = true
10    wait(5)
11    Debounce = false
12    end
13 
14if Pressed == true and Debounce == false then
15    print("Pressed Again")
View all 24 lines...

2 answers

Log in to vote
1
Answered by
DevingDev 346 Moderation Voter
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.

1if not debounce then 
2    humanoid:EquipTool(sword)
3    setDebounce()
4else
5    humanoid:UnequipTools(sword)
6    setDebounce()
7end

Here is the complete script.

01-- Services
02local replicatedStorage = game:GetService("ReplicatedStorage")
03local playersService = game:GetService("Players")
04local userInputService = game:GetService("UserInputService")
05 
06-- Player
07local player = playersService.LocalPlayer
08local character = player.Character
09local humanoid = character:WaitForChild("Humanoid")
10 
11local sword = replicatedStorage:FindFirstChild("Sword")
12 
13local debounce = false
14 
15local function setDebounce()
View all 31 lines...

Please feel free to ask any questions you might have about my solution, and how I came up with it.

0
Thanks dude! Dec_ade 47 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

Because it says in the first if statement to set Pressed true and after the 5 second wait timer it turns it to false the debounce so the second if statement fires.

0
so how do i fix this? Dec_ade 47 — 4y
0
well depends if you want to wait a certain amount of time to unequip it or maybe when you do a certain action like if(slash) then debounce = false like that or make the wait time longer or change the statement for the second if statement vortex767 20 — 4y

Answer this question