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

Tool isn't getting taken from players backpack. Any help? I accept answers!

Asked by
M9F 94
4 years ago

So I'm creating a script that takes the players tool once they stop touching a seat. Nothing is happening and I'm getting an output that says "attempt to index nil with "Backpack". It is not in a local script. Any help would be greatly appreciated!

local deBounce = false

local function takeRocket(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if deBounce == false then
        deBounce = true
        wait(1)
        local rifle = player.Backpack.AssultRifle
        rifle:Destroy()
        deBounce = false
    end
end
script.Parent.TouchEnded:Connect(takeRocket)

1 answer

Log in to vote
1
Answered by 4 years ago

The error you say attempt to index nil with "Backpack" is because player is sometimes nil, if for example an Accessory's Handle touches the part, it's parent is not the Character but the Accessory so using GetPlayerFromCharacter on it will return nil, you can fix this by checking if player is not nil as the other guy did:

local deBounce = false

local function takeRocket(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)

    -- This will return if player does not exist
    if not (player) then
        return
    end

    if deBounce == false then
    ...

Other issue is that if rocket tool is equipped, it's not in Backpack but in the Character so you should look for the tool in both like this:

local function takeRocket(hit)
    local Character = hit.Parent

    local player = game.Players:GetPlayerFromCharacter(Character)

    if deBounce == false then
        deBounce = true
        wait(1)
        local rifle = player.Backpack:FindFirstChild('AssaultRifle') or Character.AssaultRifle
        rifle:Destroy()
        deBounce = false
        ...
0
I used a different way but I'll still accept M9F 94 — 4y
Ad

Answer this question