Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Plr is a nil value?!

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?

2 comments

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.

0

so how should I fix it?

1 answer

✓ Accepted 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)

1 comment

0

its ok now. thx for the answer. Even though i've fixed it already... but thx anyways. :)

This discussion is preserved as it was. New answers, comments, and votes are closed.