Hi ScriptingHelpers community,
I saw that this question have been made before but I'll be glad if some of you can answer it anyway so I can understand better what am I doing wrong.
I have this script in order to print on the terminal when the player press a Key Down and the same thing when the Key is Up:
local PlayersService = game:GetService('Players') local LocalPlayer = PlayersService.LocalPlayer Mouse = LocalPlayer:GetMouse() function KeyUp(key) if (key == "q") then print('Key is Up') end end function KeyDown(key) if (key == "q") then print('Key is Down') end end Mouse.KeyUp:connect(KeyUp) Mouse.KeyDown:connect(KeyDown)
The problem is that when I run the game with the script it says: - ServerScriptService.Script:4: attempt to index field 'LocalPlayer' (a nil value)
I have the script on the 'ServerScript' folder and I also tried with the 'StarterPlayerScripts' folder but the same error appears. What am I missing?.
I'm new with this hole thing called 'Roblox Scripting' and I don't know a lot of things about the API so I'll be glad if some of you can answer my question.
In the meantime, thank you so much for your attention.
There are two sides to Roblox games. There are the clients, and there is the server. The server doesn't, and shouldn't, handle user input.
Think of this; when the server tried to find a LocalPlayer
, which player does it pick? There may be multiple players connected to the game, and it can't just pick one at random.
Your script works in Studio because everything is ran on your computer locally, and there is no server. In an actual game, that's not the case.
The solution is to use a LocalScript
, in StarterPack
, or somewhere else LocalScripts can run. Then the Local Script will replicate inside the players when they join, and they'll run locally.
Code ran on the client normally doesn't replicate to the server if Network Filtering is enabled.
-- Local Script in StarterPack --// Services local Players = game:GetService("Players") -- About the same as game.Players --// Local Variables local plr = Players.LocalPlayer
Now, to get user input you should not use KeyDown
. KeyDown is deprecated. Instead, I recommend UserInputService
.
Here's an example of the finished code:
-- Local Script in StarterPack --// Services local Players = game:GetService("Players") local UIS = game:GetService("UserInputService") --// Local Variables local plr = Players.LocalPlayer -- Input Began UIS.InputBegan:Connect(function(input) if input.KeyCode == Enum.KeyCode.Q then print("Q was pressed!") end end) -- Input Ended UIS.InputEnded:Connect(function(input) if input.KeyCode == Enum.KeyCode.Q then print("Q was let go!") end end)