Does LocalPlayer work in a script?

I have a script on the server which when a RemoteEvent fired from the client than it sets the players humanoid.WalkSpeed to 16 after it sets it to zero when the player joins.

local players = game.Players
local characterPlayer = players.LocalPlayer
local character = characterPlayer.Character

game.Players.PlayerAdded:Connect(function(player)
	character.Humanoid.WalkSpeed=0
end)

game.ReplicatedStorage.CanWalkRemote.OnServerEvent:Connect(function(player)
	character.Humanoid.WalkSpeed=16
end)
1 Like

No, game.Players.LocalPlayer is not defined in server scripts.

So how do I get the character then?

local players = game:GetService("Players")

players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		--Do stuff with character.
	end)
end)

LocalPlayer only works in local scripts. That’s because that gets the player the client controls. It is just nonsensical on a server because there is no player to consider the primary player. However you can’t still use the player argument passed through. Remote events will pass the player as the first thing and that will work just fine even if set by localPlayer because it’s just a reference.

2 Likes

But I get an error?

I thought you were trying to get the player not the character, check the script I just provided.

That’s because you are using local player in a server script. Local player doesn’t mean anything in a server script. Inside the functions instead of just saying character. You should say player.Character

player.Character.Humanoid.WalkSpeed=0

This will work because player is actually passed to the functions. So in a sense that player parameter in your functions is the “LocalPlayer”.

The server just doesn’t know what local player means because it doesn’t control any of the players.

I forgot you could do this from a local script.

game.Players.LocalPlayer.Character.Humanoid.WalkSpeed