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

How do you fix attempt to index nil with 'FindFirstChild'?

I've got this script inside a part that is in Workspace that when someone goes over it does some code, but I began seeing this error:

attempt to index nil with 'FindFirstChild'

Here is the script:

script.Parent.Touched:Connect(function(hit)
	if hit then
		wait(1)
		local player = nil
		
		-- Checking to see if the part that hit it is a character
		if hit.Parent:FindFirstChild("Humanoid", true) then -- this is where it is erroring
			player = game.Players:GetPlayerFromCharacter(hit.Parent)
		-- Special case where a hat hits the spawn rather than a limb
		elseif hit.Parent.Parent:FindFirstChild("Humanoid", true) then
			player = game.Players:GetPlayerFromCharacter(hit.Parent.Parent)
		end
	end
end)

1 comment

0

Remove "true" on lines 7 and 10.

1 answer

script.Parent.Touched:Connect(function(hit)
    if hit then
		wait(1)
        local player = nil
        -- Checking to see if the part that hit it is a character
        if hit.Parent:FindFirstChild("Humanoid") then 
            player = game.Players:GetPlayerFromCharacter(hit.Parent)

		 end
   		 if hit.Name == "Handle" and hit.Parent.Parent:FindFirstChild("Humanoid") then
       		 player = game.Players:GetPlayerFromCharacter(hit.Parent.Parent) 

         end
     end
end)

With the if statement, if it finds the Humanoid, it will move on, and if it doesn't it won't. You don't need to tell it that if the search is true to move on, because it will know to move on if it finds the Humanoid.

The second part with the elseif is giving the script the same guidance as if it wasn't touched by the handle of a hat. With the edit I did, it searches if the thing that hit it was a handle, and if it is named Handle, it will search for the Humanoid. If all of that is true, then the player variable will be set.

I hope this helps!

4 comments

0

I hate to say this but the same error is still appearing. Thank you for your help though!

0

Okay, I have edited, and tested it in studio. Everything works fine. Also, you should be using a server script if you aren't already

0

Huh, very odd, I am using a serverscript in the part. The code works it just gives of this error. Is it okay if I don't fix it or should I still fix it.

0

By all means, you can stick with your script if you chose. What is the error it gives of though?

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