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

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

Asked by 3 years ago
Edited 3 years ago
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)
0
Im trying to make a pvp zone in my game CrownedFigure 45 — 3y

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

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

Ad

Answer this question