FindFirstChildOfClass Usage

Hey guys,

The example given on developer.roblox.com is as follows

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

local humanoid
    while not humanoid do
        humanoid = 
        character:FindFirstChildOfClass("Humanoid")
        
        if not humanoid then
            character.ChildAdded:wait()
        end
 end

Is it absolutely necessary to check for

while not humanoid do
     humanoid = character:FindFirstChildOfClass("Humanoid")
    
    if not humanoid then
        character.ChildAdded:wait()
    end
end

as wouldn’t all the children of character already already be available from this line?

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

How about just doing this?

local humanoid = character:FindFirstChildOfClass("Humanoid")

player.Character or player.CharacterAdded:Wait() yields the script until the Character property of the player isn’t nil, which is when the CharacterAdded event fires. I would also recommend changing :wait() to :Wait() as :wait() is deprecated.

That’s only going to return nil if the humanoid doesn’t already exist. IIRC, the humanoid doesn’t yet exist when this fires.

Instead, there are a few options:

1- :WaitForChild(), the built-in method.
or,
2- Create your own function, such as the one here.

Great, Thank you.

So could I get the humanoid this way instead?

local humanoid = character:WaitForChild("Humanoid")

Yeah, think that’s the most common and secure method as it ensures the humanoid exists before letting the rest of your code run.