The gist of things
The issue here is that the player and the Character load at different times, as the player loads first and the Character and all scripts , guis, and tools inside the player load after.
Unfortunately, the character loads slower than the script runs, which means you would be getting the character property of the player without it existing. That is the reason why that line of code errored.
Solutions
There are a couple of solutions here, first, you can simply not use the name of the character as the names of the player and the character should be identical.
game:GetService("Players").PlayerAdded:Connect(function(plr)
print(plr.Name)
end)
The second solution would be to use the character added event, which there are two ways of utilizing. The ``RBXScriptSignal`` object has two functions of it that can be used here, the ``Wait()`` functions and the ``Connect()`` function. The wait function yields until the signal is fired, and returns a tuple of arguments
game:GetService("Players").PlayerAdded:Connect(function(plr)
local char = plr.CharacterAdded:Wait()
print(char.Name)
end)
This method is not recommended as it holds up all other parts of the PlayerAdded event (its current thread) as it waits for the event to be fired
A far better way to do this would be to use the :Connect() function of the RBXScriptSignal
game:GetService("Players").PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(char)
print(char.Name)
end)
end)
Note: the plr.CharacterAdded:Wait() method is not used commonly but the plr.CharacterAdded:Wait() part it self can be useful outside the player added event, for example, in local scripts outside the Character, many people simply do
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
to make sure the character exist before using it
Hopefully this helped and have a nice day scripting!
1 comment
Thanks that did the trick!