Is there something more efficient than FindFirstChild?

I have a couple of if statements in my scripts that use the FindFirstChild function, but the problem is that every time it runs and it doesn’t find a child of the name i put, it creates an error. Is there a more efficient way I can find if something has a child without creating a bunch of errors every time it doesn’t?

WaitForChild waits 4 a child and thus prevents the script from running b4 child is created, which can result in errors.

Eg:

local Cup = game.workspace:WaitForChild("Cup")

This function is important mainly in localscripts as the script may run b4 the object is replicated from client to server.

More info on WaitForChild

1 Like

nope, it still give me an error: attempt to index nil with ‘WaitForChild’

Then its bcuz ur object is nil or not created. Cud u show the script in tht case? Probably doesn’t have to do anything with FindFirstChild

yes, thats the problem.
when the object doesn’t exist it creates an error

Well… WaitForChild must solve tht issue else its error in either script or the object replication.

the variable must not be an Instance.

guys lets not have an argument in my devforum post okay

In tht case just do:

if object ~= nil then -- ur object or instance here
--rest of the code

This just confirms tht the child isnt a nil value saving a lot of errors.

dude idk if my script is just cursed or something but it still gives the same error: attempt to index nil with ‘Humanoid’

Cud u show the script pls so we can gather more conclusions?

--raycasting stuff ^^^
		local model = hitPart:FindFirstAncestorOfClass("Model")
		if model.Humanoid ~= nil then
--the stuff i want to run vvv

R u trying to get a child from hitPart if not the error is due to the fact model is nil.
It means that :FindFirstAncestorOfClass("Part") function couldn’t find an ancestor with ClassName property set to hitPart

if the model is nil, why do i only get the error when attempting to reference the humanoid?

Check if the model exists by

if model then

also if im correct that means if i were to send the raycast onto a model then it wouldnt create an error correct? ill try that right now and see what happens

You can’t really avoid doing FindFirstChild if-checks when doing raycasting. It gives you information about a single point in time, so you can only get information about what exists in that instant. In this case, FindFirstAncestorOfClass can fail. There might not be a model holding the hitPart.
Try this:

local model = hitPart:FindFirstAncestorOfClass("Model")
if model and model:FindFirstChildOfClass("Humanoid") then
    -- we know this is a character model, but we haven't checked if it's a player or npc yet
end
2 Likes

Excuse me asking this but wt iw model, is it a character?

ok yes i was correct, now it just says Humanoid is not a valid member of Model “Workspace.Model”

Well tht means ur model doesnt have a humanoid or use

model:WaitForChild("Humanoid")