问题
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