local canpress = true script.Parent.Touched:connect(function(hit) local plrr = hit.parent local plr = game.Players:FindFirstChild(plrr) local m = plr:GetMouse() local canpress = true m.KeyDown:connect(function(k) k = k:lower() if k == "e" then if canpress == true then print(plr) canpress = false wait(1) canpress = true end end end) end) script.Parent.TouchEnded:connect(function() canpress = false end)
i wouldn't be surprised if there is a big error in there. i am trying to make it so if you touch the brick and tap "e" it prints the players name (printing the name is for testing.)
The problem is that when you used FindFirstChild
, it returned nil
(player wasn't found). Meaning on line 6 you were doing nil:GetMouse()
, which will obviously throw an error. A fix would be to check if the player exists, and if it does, execute the code.
Make your script a LocalScript
, as user input should not and cannot be handled by the server.
-- Local Script, in StarterGui local client = game:GetService("Players").LocalPlayer local canpress = true local UserInputService = game:GetService("UserInputService") local part = workspace.Part -- Path to your part goes here. UserInputService.InputBegan:Connect(function(input, gpe) if gpe then return end -- if they're chatting end the function! if input.KeyCode ~= Enum.KeyCode.E then return end -- If they didn't press E, end the function if canpress then print(client) canpress = false wait(1) canpress = true end end) part.Touched:Connect(function(hit) -- connect is deprecated, use Connect' -- Do something... end) part.TouchEnded:Connect(function() canpress = false end)
The KeyDown
event is deprecated, use InputBegan
from UserInputService
. The UserInputService
can detect more than computer input, it can detect mobile input and console input, which can help make your game cross-platform compatible if desired. It is also much more consistent than KeyDown
.
Finally, your indentation is extremely poor. Your code is indented inconsistently, in some lines you have good indentations and in others you don't. Though poorly indented code does not affect the result of your code, it is important to keep code clean and tidy, or else even you yourself might not know what the heck you wrote.