Detect if key is just pressed?

I have a module script, and I want to know if the P key is JUST pressed. Not held down or anything. But how would I set that in a module?

For example, if you want to know if a key was just pressed in a while loop while it’s still running without using UserInputService.InputBegan outside of the loop.

Is it okay if I can see your script?

while wait() do
    if require(game.ReplicatedStorage.ModuleScript).is_key_just_pressed("P") then
        print("P is just pressed")
    end
end

I currently do not have a module script function setup for this right now which is why I’m asking on how to do it.

I don’t think that you can check if a player has pressed a key without using UserInputService

1 Like

You should use the UserInputService. It’s much easier to use and will be able to have your functions you want to make happen work with greater speed.

UserInputService Link

You in fact can, if you use the mouse there is a way to detect key presses.
However this is superseded.

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

mouse.KeyPressed:Connect(function(key)

end)

That is fine and all, but I want to find out if they pressed the button inside a loop, not outside. Something like Godot’s method would be appreciated.

What’s in your module script? This might help me a bit.

I use UserInputService to check if a key is down. That is pretty much everything in the Module.

Put this in your module script

local USI = game:GetService("UserInputService") 

local ifKeyboardP = {
	
	"",

	USI.InputBegan:Connect(function(input)
		if input.KeyCode == Enum.KeyCode.P then
			print("Player pressed P")
		end
	end)
	
	
}

return ifKeyboardP

And this in your normal script

local module = require(game.ServerScriptService.ModuleScript) --Change this to the location of your module script
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.P then
		print(module[1])
	end
end)

When it prints unfortuantly it will just print a blank message before that but I don’t think that’s too much of a problem. Also I could not get the USI to only work in the loop but it’s the only way I know how to do it.

1 Like

Just as xxxXMadStudioXxxx1st said, use that in your module script. Your local script need only include…

require(game.ReplicatedStorage.ModuleScript) --or wherever it is

UserInputService can run from a local script or module script that is required by a local script.

1 Like