Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get local character in server test?

Asked by 6 years ago

This is part of a longer script, but I've narrowed down that the problem is occurring here.

local player = game.Players.LocalPlayer
local character = player.Character

When I run this with the "Play" button, it works fine. But when I run a server test with 2+ players, it stops on the line "local character = player.Character" line. Does local character not work in servers or is there another method I should use?

1 answer

Log in to vote
0
Answered by
theCJarmy7 1293 Moderation Voter
6 years ago
Edited 6 years ago

The Character of a player loads in a little bit after the player object itself loads, and thus when the localScript first loads, the Character is nil. A common way to get around this is to use the following code:

local char = player.Character or player.CharacterAdded:wait()

With the or in there, when running this script, the game will first check if player.Character is a thing, and if it is, will return player.Character, however, if player.Character is not a thing yet (hasn't loaded yet) it will run player.CharacterAdded:wait() and wait for the character before returning it.

Since you didn't specify in your question, I assumed you used a LocalScript, if you used a ServerScript then you can't use LocalPlayer, because it will return nil instead of a player object. This occurs because there is one server, and many clients. LocalScripts are run on the client, which let's you use LocalPlayer, however, ServerScripts (obviously) run on the server, and don't have a LocalPlayer to reference.

This works when using solo play, because (at least I don't think) studio doesn't run a server in the background while you play as the client. Although, I believe studio does recognize some things that shouldn't be, as, in my experience, LocalScripts do not run in the workspace during solo play, which is how they should work.

0
So yea, I had everything in a server script instead of a local script. However, I found a much easier way to do this. I can just say script.Parent.Parent to get the character holding my tool. Thanks for setting me straight on local/server scripts. tygerupercut3 68 — 6y
Ad

Answer this question