Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 3 years ago
Edited 3 years ago

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

Log in to vote
1
Answered by 3 years ago

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.

:)

Ad
Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

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

Answer this question