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

Why does my script have errors like attempt to index nil with 'Backpack or Destroy'?

script.Parent.Touched:Connect(function(Char)
	local plr = game.Players:GetPlayerFromCharacter(Char.Parent)
	local backpack = plr.Backpack
	local sword = game.Lighting.Storage.ClassicSword:Clone()
	local con = game.Lighting.Storage.HasPvP:Clone()
	if not backpack:FindFirstChild("HasPvP") then
		sword.Parent = backpack
		con.Parent = backpack
		else
		end
end)

script.Parent.TouchEnded:Connect(function(Char)
	local plr = game.Players:GetPlayerFromCharacter(Char.Parent)
	local backpack = plr.Backpack
	if backpack:FindFirstChild("HasPvP") then
		backpack.HasPvP:Destroy()
		backpack.ClassicSword:Destroy()
		Char.ClassicSword:Destroy()
	else
	end
end)

1 comment

0

Im trying to make a pvp zone in my game

1 answer

✓ Accepted answer

You're trying to access Backpack and the Destroy function of something that doesn't exist, so basically nil.Backpack and nil:Destroy(). I'm guessing that this part is touching another part of itself, and "plr" gets set to nil in line 2 and line 14 because the part doesn't have a player associated with it.

Just do a simple check to make sure "plr" isn't nil before the rest of the code executes:

script.Parent.Touched:Connect(function(Char)
    local plr = game.Players:GetPlayerFromCharacter(Char.Parent)
    if plr then
	local backpack = plr.Backpack
    	local sword = game.Lighting.Storage.ClassicSword:Clone()
    	local con = game.Lighting.Storage.HasPvP:Clone()
    	if not backpack:FindFirstChild("HasPvP") then
        	sword.Parent = backpack
        	con.Parent = backpack
    		end -- also you don't need an else block here if it's just empty
	end
end)

-- do the same thing in the TouchEnded event

you should probably also put the sword in ReplicatedStorage or ServerStorage because having models mixed up with postprocessing effects and all that will be an organization nightmare later on

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