I made a coin collecting script, but when the coin touches something that’s not a player the script still runs which is why I get this error.
14:21:34.142 - Workspace.ElixirDrop.ElixirDropCollect:14: attempt to index nil with ‘leaderstats’
local elixir = script.Parent
local currency = "Elixir"
local amt = 1
local d = true
elixir.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and d then
d = false
local plr = game.Players:FindFirstChild(hit.Parent.Name)
plr.leaderstats:FindFirstChild(currency).Value = plr:FindFirstChild("leaderstats"):FindFirstChild(currency).Value + amt
elixir:Destroy()
end
end)
You aren’t taking into account that FindFirstChild will return nil if the child doesn’t exist. You might have an NPC or something that has a humanoid but isn’t a player. Try checking if plr exists before indexxing it.
The coin is in server script storage could that be affecting it?
This script is the coin’s parent
local Debris = game:GetService("Debris")
local spawner = game.Workspace.Spawner
local elixir = script.ElixirDrop
local r = 250
while wait() do
local elixirclone = elixir:Clone()
local x,z = spawner.Position.X,spawner.Position.Z
x,z = math.random(x - r,x + r),math.random(z - r,z + r)
local pos = Vector3.new(x,spawner.Position.Y,z)
elixirclone.Parent = workspace
elixirclone.Position = pos
Debris:AddItem(elixirclone, 10)
end
local elixir = script.Parent
local currency = "Elixir"
local amt = 1
local d = true
elixir.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and d then
d = false
local plr = game.Players:FindFirstChild(hit.Parent)
if plr then
plr("leaderstats"):FindFirstChild(currency).Value = plr:FindFirstChild("leaderstats"):FindFirstChild(currency).Value + amt
end
elixir:Destroy()
end
end)
But I get this error
15:43:20.694 - Workspace.ElixirDrop.ElixirDropCollect:9: attempt to index nil with 'FindFirstChild'