local enabled = true local function onInputBEGAN(inputObject, gameprocessed) if inputObject.KeyCode == Enum.KeyCode.E then print("pressed") enabled = false end end local function onInputENDED(inputObject, gameprocessed) if inputObject.KeyCode == Enum.KeyCode.E then print("released") enabled = true end end if enabled == true then game:GetService("UserInputService").InputBegan:connect(onInputBEGAN) elseif enabled == false then game:GetService("UserInputService").InputEnded:connect(onInputENDED) end
The script should print 'pressed' when the 'E' key is pressed and should print 'released' when it's released, but it's not working. There are no errors printed in the output either.
What's wrong with my script? Is there an easier, more efficient way to do this?
Please help.
It's because of the if statement. The script thinks it has done its job once it completes that if statement and will just need to listen to any events necessary. Since enabled is true at the beginning of the script and when the if statement is run, the only event the script has to listen to is InputBegan.
For your situation, just make a temporary event. A temporary event means it can get disconnected when you need to get rid of it. Since temporary events are somewhat buggy, you will need to define the variable before defining the temporary event. We will then need to set the new OnInputENDED variable equal to the event and anonymous function.
We will take the anonymous function and execute any code we need to execute. Once you are all done with that, we will need to :disconnect
the temporary event at the end.
local enabled = true local function onInputBEGAN(inputObject, gameprocessed) if inputObject.KeyCode == Enum.KeyCode.E then print("pressed") enabled = false local onInputENDED --We just need to let the script know, hey this is real. May be nothing but it's real. onInputENDED = game:GetService('UserInputService').InputEnded:connect(function(inputObject) --We're making an anonymous function, this will be our event we're connected to. if inputObject.KeyCode == Enum.KeyCode.E then print('released') enabled = false onInputENDED:disconnect() --Here, the event gets tossed out. This way you're not seeing double of prints and the code isn't doing double. end end) end end game:GetService("UserInputService").InputBegan:connect(onInputBEGAN)