Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make it so the script prints the LocalPlayers' name?

local player = game.Players.LocalPlayer.Name --This is the part that doesn't work, but I can't make it work
local playername = game.Workspace:FindFirstChild(player)

if script.Toggled.Value == 1 then
	
print(playername)

end

1 comment

0

This is fairly basic but I need it for something more complicated

3 answers

In your script, player is in fact that player's name. playername will be nil


If you want their character, you shouldn't be using workspace:FindFirstChild(player). You should just get the player.Character property:

local player = game.Players.LocalPlayer

local character = player.Character

However, the Character does not load immediately. It will start nil. For a LocalScript, you can :wait() for the .CharacterAdded event to fire:

local player = game.Players.LocalPlayer

local character = player.CharacterAdded:wait()

In the off chance that the Character loads before the script, this would miss the character. Thus, you could do this:

local player = game.Players.LocalPlayer
local character
if player.Character then
	character = player.Character
else
	character = player.CharacterAdded:wait()
end

but that's long and wordy. You can shorten it to simply:

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:wait()

Variable Names

Variable names are really important. You want to pick them well because they let you think about the script.

In your example, player is the name of the player, and playername is the player's character.

That makes no sense. Use meaningful variable names.

2 comments

0

I think there is a misunderstanding. I'm trying to get the name of the localplayer, and this script find the character. Is there anyway that the localplayers name can be found using this?

0

As I said, what you had was the player's name (just the player =, not the playername, as I explained). But that's the improper way to get the character. This is the proper way to get the character.

Is this a local script or a normal script?

local player = game.Players.LocalPlayer --This only works in a local script.

If you'd prefer using a normal script, then you could put it in the StarterGui, so when a player joins it would move into their PlayerGui. To find the player, you'd then do:

local player = script.Parent.Parent

Hope this helps :-)

Put this in a LocalScript

print(game.Players.LocalPlayer.Name)

This discussion is preserved as it was. New answers, comments, and votes are closed.