Attempt To Index Nil With FindFirstChild

`

20:52:48.922 - Workspace.darkelixir.darkelixirCollect:13: attempt to index nil with ‘FindFirstChild’

`

local darkelixir = script.Parent
    local currency = "Dark Elixir" -- rename to the currency that you want to use
    local amt = 1 -- How many coins the player gets

local d = true

darkelixir.Touched:Connect(function(p)
  if p.Parent:FindFirstChild("Humanoid") and d then
     d = false

    local plr = game.Players:FindFirstChild(p.Parent.Name)

    plr:FindFirstChild("leaderstats"):FindFirstChild(currency).Value =  plr:FindFirstChild("leaderstats"):FindFirstChild(currency).Value + amt

    darkelixir:Destroy()
  end
end)
1 Like

You’re being very generous with your use of FindFirstChild. Because of that, I’m not sure where exactly the error is, but it’s occurring because something is returning nil. This may be because of how you’re finding the player, which is an unusual way I haven’t really seen before.

For touched events, I personally do

part.Touched:Connect(function(hit)
     local player = game.Players:GetPlayerFromCharacter(hit.Parent) -- find if player exists
     if player then
          -- code
     end
end)

Also, this line is a bit over complicated. Unless the player will be touching this part instantly upon join, you won’t need to wait for leaderstats to be added to the player.

plr.leaderstats[currency].Value = plr.leaderstats[currency].Value + amt
3 Likes

It’s now saying that leaderstats is nil

11:34:14.013 - Workspace.darkelixir.darkelixirCollect:13: attempt to index nil with 'leaderstats'

I checked and leaderstats does exist, so I don’t know why it’s saying that