More often than not, local scripts
will load in the player before his / her character does. Because of this, it's a common procedure to give the script a chance to wait
for the character, before running the next line of code.
Sometimes people will use loops such as repeat
or while
to wait until the character doesn't equal nil, but there's actually an easier and shorter way to do this.
Solution
There's an event called CharacterAdded
for each player, and with that event, inherits a wait method
. This wait isn't exactly like the one built into the global environment, it works a bit differently. Here's an example:
1 | local Player = game.Players.LocalPlayer |
3 | local Character = Player.CharacterAdded:wait() |
Possible problem?
Now, sometimes the character actually does load on time for the script to reference it right away (it's not common, but it can happen). So in this case, using the solution above would be bad, since it would wait for the character to be added, after it's already been added. So we can fix this by simply using an or statement
, like this:
1 | local Player = game.Players.LocalPlayer |
2 | local Character = Player.Character or Player.CharacterAdded:wait() |
So, hope that helped. If you have any questions, just let me know.