✓ Accepted answer
Older scripts will use a repeat wait loop but now we have a very reliable way to wait for an event using the RBXScriptSignal Wait. note that a RBXScriptSignal should not be confused with a RBXScriptConnection which is an object passed back when using :Connect.
The standard method of waiting for the players character is to use:-
local plr = game:GetService('Players').LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
To understand how this code works we first need to know how or works. Or returns its second argument if the first is nil/false. So we first try to access the players character which if found will not be nil so no wait is needed.
If the character is not found then we run the second piece of code which will wait until the event CharacterAdded is fired and pass back any arguments in this case the character which is what we need.
This method saves both time and is more robust that just waiting in an infinite loop.
Lastly it is good to note that putting a local script in the StarterCharacterScripts folder will run each time the player spawns and since its parent is the character there is no need to use any form of checking as, local char = script.Parent will always be the character.
I hope this helps.
1 comment
Thanks, I was looking for a solid answer as well :D