Keyboard Input not working properly

Making a script that activates a sword if you press it the first time and destroys the sword if you press it the second time. However, when I press the key, both events run at the same time even though I set a variable (equipped = false). The sword script works btw, its just the keyboard input Please check this out, thanks!

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Event = ReplicatedStorage:WaitForChild("Activate")
local Event2 = ReplicatedStorage:WaitForChild("Destroy")

local equipped = false

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.F and equipped == false then
		wait()
		equipped = true
		warn("Activate")
		Event:FireServer()
	end
		if inputObject.KeyCode == Enum.KeyCode.F and equipped == true then
			wait()
			equipped = false
			warn("Destroy")
		Event2:FireServer()
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)

Change:

if inputObject.KeyCode == Enum.KeyCode.F and equipped == false then
		wait()
		equipped = true
		warn("Activate")
		Event:FireServer()
	end
	if inputObject.KeyCode == Enum.KeyCode.F and equipped == true then
		wait()
		equipped = false
		warn("Destroy")
		Event2:FireServer()
	end

to this:

if inputObject.KeyCode == Enum.KeyCode.F and equipped == false then
		wait()
		equipped = true
		warn("Activate")
		Event:FireServer()
	elseif inputObject.KeyCode == Enum.KeyCode.F and equipped == true then
		wait()
		equipped = false
		warn("Destroy")
		Event2:FireServer()
	end

What was happening, is the first if statement would run, setting equipped to true, then the next if statement would run because equipped had previously been set to true. It needs to be elseif so that only one of the if statements will actually continue with the code.

1 Like

oof rookie mistake, thanks for quick reply and helping out! :blush:

2 Likes