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

How do I fix the "attempt to index nil with 'FindFirstChild'" Problem?

I tried to make a part with a click detector inside. I also made the character name which is like this:

script.Parent.ClickDetector.MouseClick:Connect(function(characterName)

Then, I made the local character like this:

local character = workspace:FindFirstChild(characterName)

When, I try tetsing and clicking on it, I get the error called: attempt to index nil with 'FindFirstChild'

I hope you understand this problem.

2 answers

✓ Accepted answer

This happened because when the Click Detector is activated, it does not send the name of the player who activated it, but its data, it sends the player in full.

So when you use FindFirstChild, you get this error because it cannot search for it in Workspace, because we are not talking about a name, but an entire entity.

You just need to enter the following code.

script.Parent.ClickDetector.MouseClick:Connect(function(CharacterName)
	local Character = workspace:FindFirstChild(tostring(CharacterName))
end)

Note: CharacterName is the player, not your name!

Thus, the code will convert the entire entity into just one name, which is the name of the entity, hence the name of the player.

You can also do the following.

script.Parent.ClickDetector.MouseClick:Connect(function(CharacterName)
	local Character = workspace:FindFirstChild(CharacterName.Name)
	-- Or
	local Character = CharacterName.Character
	-- Because he sends us the player in full, not just his name!
end)

In short, everything.

CharacterName = Player CharacterName ~= Player.Name

Hope this helps. If you have any questions, you can ask me.

:)

Hello! This is a simple problem with the MouseClick parameter

MouseClick event returns player who clicked it. When you do :FindFirstChild(characterName), it tells the function to search for said player instance. Player instance only can be found in PlayersService. So it's obvious what's the problem...

You need to do :FindFirstChild(characterName.Name) or just simply do characterName.Character

local character = game.Workspace:FindFirstChild(characterName.Name)

-- or

local character = characterName.Character

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