Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What is FindFirstChild? What do we use it for? Why is it useful?

1 answer

This is a method (a function special to it’s class) of Instance. It is used to “safe-search” for a child of the Instance FindFirstChild() is called. If you’re unaware of a what a child is, it is a figure on a hierarchical structure, this of which is one block below the Instance.

Why is it considered a "safe-search"? Well, when we try to reference an Instance that is a block below the Instance we specify, there is a chance it may not have loaded, or may not exist. This scenario is a lot more common than you will believe. The code will error if we try to step to it via Instance.ChildName or use other means that are directly looking for it, and came up with nothing. FindFirstChild() will not consider the child missing an error, and simply will return nil

It is commonly used to condition a program to only perform an action if the child is found, without causing problems if it isn’t. An example of this can be seen with detecting if a Player touched a Part. There is a partial danger to using :GetPlayerFromCharacter(), the Character is theoretically Hit.Parent, but this can truly be anything but. So to narrow Hit.Parent to a more likely chance of It being a Character, we filter for a Humanoid. But there’s just one problem, we cannot guarantee there will be a Humanoid, just like we can’t for a Character, so how do we look for one without causing an error? FindFirstChild():

local Players = game:GetService("Players")

local Part = workspace.Part

Part.Touched:Connect(function(Hit)
    if (Hit.Parent:FindFirstChild("Humanoid")) then
        local Player = Players:GetPlayerFromCharacter(Hit.Parent)
        print(Player.Name) 
    end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.