Riki
Riki

Reputation: 1

Roblox - attempt to index nil with 'leaderstats'

Can someone tell me how can I fix this error that shows up when I run my script? Thanks

line 4: Workspace.Slide1.PointsPart.Script:4: attempt to index nil with 'leaderstats'
script.Parent.Touched:Connect(function(hit)
    local player = hit.Parent:FindFirstChild("Humanoid")
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    if plr.leaderstats.Points.Value >= 0 then
        wait()
        script.Disabled = true
        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        plr.leaderstats.Points.Value = plr.leaderstats.Points.Value +5
        wait(0.5)
        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        script.Disabled = false
    end
end)

Upvotes: 0

Views: 522

Answers (2)

C luck
C luck

Reputation: 26

You could change it to this

script.Parent.Touched:Connect(function(hit)
    local player = hit.Parent:FindFirstChild("Humanoid")
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    if plr and plr.leaderstats.Points.Value >= 0 then
        wait()
        script.Disabled = true
        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        plr.leaderstats.Points.Value = plr.leaderstats.Points.Value +5
        wait(0.5)
        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        script.Disabled = false
    end
end)

the compiler will calculate the instance "plr" first,

if it isn't nil, then the compiler will calculate "plr.leaderstats.Points.Value >= 0"

and this process called "Short-Circuit Evaluation"

Upvotes: 0

Kylaaa
Kylaaa

Reputation: 7188

The Touched event fires for anything that touches the part. You are not handling the case that a part isn't a child of a Player's Character.

local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not plr then
    return
end

if plr.leaderstats.Points.Value >= 0 then

Upvotes: 1

Related Questions