Roblox - attempt to index nil with 'leaderstats'

你。 提交于 2021-01-29 18:22:01

问题


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)

回答1:


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



回答2:


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"



来源:https://stackoverflow.com/questions/63622907/roblox-attempt-to-index-nil-with-leaderstats

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!