One time Key Down

Hello,

So, I want to make one time Key Down. For example. I hover with mouse on part and UI pops up that says “Press E to teleport”, so when player hovers onto a part it gives player ability to press E or if it is not hovering the function should be disabled. Here what I got:

Script Enable/Disable Key

if enableE then

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

mouse.KeyDown:connect(function(key)
	if key == "e" then
		
		enableE = false

		teleE = true
    
		wait(5)

		completed = true
		
	end
end)	

else

----nothing here	

end

Script On Mouse Hover

while wait() do
if Mouse.Target ~=nil and Mouse.Target.Name == ‘Intera1’ then

enableE = true

else

	enableE = false
end

In terms of a one-time keydown, you’re looking to disconnect the function rather than not do anything based on a variable. It’s good practice to get rid of what you don’t need anymore.

-- I will keep KeyDown for you.

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local PlayerMouse = LocalPlayer:GetMouse()

local mouseKeyDown do
    mouseKeyDown = PlayerMouse.KeyDown:Connect(function (key)
        if key:lower() == "e" then
            mouseKeyDown:Disconnect()
            -- Other code, like enableE = false
        end
    end)
end

Aside from this, there are other things I want to point out.

Mouse.KeyDown is deprecated and shouldn’t be used for new work. UserInputService and ContextActionService are the preferred method of binding input to functionality. Try using those in the future.

GetService is the canonical way to fetch a service over dot syntax. Service names can change and some of them are not named properly. You also want to do this for the sake of future consistency. GetService undoubtedly fetches services if they exist, dot syntax does not.

I have a thread lurking around in Community Resources titled “The While-Wait-Do Idiom” which looks down upon the way the while loop was used here. In general I think you’re reinventing the loop a little here, but I’m not going to reconstruct your code, so I can just point out preferred practices.

while true do
    enableE = conditionsThatEvaluateToASingleBool
    wait()
end

In terms of the while loop, this is what I’d do.

2 Likes

Just something I noticed with your while loop - using “wait()”

Read this article on why you shouldn’t use

while
    -- do something
    wait()
end

For the purposes of this thread, that’s irrelevant. Removing the wait statement will crash the client due to not debouncing your wait statement and there’s no reason to reinvent the wheel. I’m simply suggesting a change that uses the while condition appropriately.