What loads first?
This should bring up the question: what actually loads first when your game starts, the script, or the object you're trying to access?
Well, the answer is unclear. Most of the time, your local scripts inside the player will load before the object you're trying to get. This makes it so we have to make our script wait for whatever we're looking for, then continue.
Solution
Most of the time, using a loop or WaitForChild is used to accomplish this. However, WaitForChild only works for getting an object that's inside of the object you're calling the method on. The Character of the player is not a child of it, so we can't use WaitForChild in this scenario.
Alternatives
We can however use loops to wait until the character is found, however this code can be a bit lengthy and messy looking for something that's supposed to accomplish a simple task. I'll show you a better way to do this, but here's how it'd look using a while loop and repeat loop:
local Player = game:GetService("Players").LocalPlayer
local Char = Player.Character
if not Char then
repeat wait() Char = Player.Character until Char
end
if not Char then
while wait() and not Char do
Char = Player.Character
end
end
A better solution
A better solution in this case, would be utilizing the CharacterAdded event, with it's built-in wait function. The wait function called on CharacterAdded is not like the wait function built into the script environment, but has the same concept.
Saying Player.CharacterAdded:wait() will yield your code until the character has been added to the player, while also returning the character. Which is perfect for waiting for the player's character.
Here's an example:
local Player = game:GetService("Players").LocalPlayer
local Char = Player.Character or Player.CharacterAdded:wait()
print(Char)
Hope this helped, let me know if you have any questions.
2 comments
I wanted to asnwer m8 >:L
Thanks a lot, it helped a lot.