how do I detect a key pressed by a player (for example the '' E '' key) I created this script, but it doesn't work:
game.Players.PlayerAdded:Wait() local player = game.Players.LocalPlayer local mouse = player:GetMouse() mouse.KeyDown:Connect(function(keydowned) if keydowned == 'e' then print('Script') end end)
Sir I believe the event that you are using is deprecated (keydown), meaning its no longer recommended to be used. Instead, use UserInputService.
local uis = game:GetService("UserInputService") local player = game.Players.LocalPlayer uis.InputBegan:connect(function(key, gameevent) --Second paramater check if input is game related such as typing in chat *I believe* if gameevent then return end if key.KeyCode == Enum.KeyCode.E then -- checks if key pressed is E print('E has been pressed') end end)
Don't use mouse.KeyDown, its deprecated. Instead, use UserInputService
Here's a basic example of how to activate a function when the E key is pressed:
local UIS = game:GetService("UserInputService") -- Get UserInputService UIS.InputBegan:Connect(function(input, gpe) -- input is the InputObject and gpe is gameProcessedEvent, this is to make sure the function doesn't activate if the user is chatting if gpe then return end -- If the player is chatting, do nothing if input.KeyCode == Enum.KeyCode.E then -- If the KeyCode is E then print("Hello World!") end end)
You can also use UserInputService to detect mouse presses
local UIS = game:GetService("UserInputService") UIS.InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then print("Mouse Click") end end)
You should look at these threads to know what UserInputService
can do
UserInputService: http://https://developer.roblox.com/en-us/api-reference/class/UserInputService
The KeyCode Enum: https://developer.roblox.com/en-us/api-reference/enum/KeyCode
Types of userinput: https://developer.roblox.com/en-us/api-reference/enum/UserInputType