Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Plr is a nil value?!

Asked by 8 years ago

I'm trying to script a door which requires a key to open it. Here is the script:

script.Parent.Touched:connect(function(hit)
    if hit.Parent ~= nil then
        local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
        if plr.Backpack:FindFirstChild('Temple Key') then -- The problem!!!
            script.Parent.Transparency = 0.7
            script.Parent.CanCollide = false
            plr.Backpack['Temple Key']:Destroy()
            wait(5)
            script.Parent.Transparency = 0
            script.Parent.CanCollide = true     
        end
    end
end)

When I touched the door (with and without the key), the output stated this error: 16:56:04.906 - Workspace.Union.Script:4: attempt to index local 'plr' (a nil value)

How am I able to fix line 4 of the script above?

0
You're assuming that some brick didn't just hit the part. Line 2 would tell the script to proceed, however line 3 will return nil if the brick's parent isn't a character model. Therefore line 4 will give the mentioned error. M39a9am3R 3210 — 8y
0
so how should I fix it? starlebVerse 685 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.
script.Parent.Touched:connect(function(hit)
    local human = hit.Parent:findFirstChild("Humanoid")
    if (human ~= nil ) then -- check if it is a player  
        local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
        if plr.Backpack:FindFirstChild('Temple Key') then 
            script.Parent.Transparency = 0.7
            script.Parent.CanCollide = false
            plr.Backpack['Temple Key']:Destroy()
            wait(5)
            script.Parent.Transparency = 0
            script.Parent.CanCollide = true     
        end
    end
end)

0
its ok now. thx for the answer. Even though i've fixed it already... but thx anyways. :) starlebVerse 685 — 8y
Ad

Answer this question