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

i'm trying to unequip my pet but it keeps saying "attempt to index nil with 'Destroy'"?

Asked by 2 years ago

i am trying to put pets into my game but it keeps saying "attempt to index nil with 'Destroy'"

the whole lines are game.ReplicatedStorage.Remotes.UnequipPet.OnServerEvent:Connect(function(player, pet) if player.Character.Humanoid.Health ~= 0 then player.Character:FindFirstChild(pet):Destroy() end end)

2 answers

Log in to vote
0
Answered by 2 years ago

A couple things could be wrong,

The first thing is, if "pet", the variable you are trying to send through this event is an object / instance, then it won't work. FindFirstChild takes a string as a parameter, if you are sending the object then you can just do pet:Destroy()

If "pet" represents a string, that means that the pet doesn't exist in the specified place, in your character in this example, as the FindFirstChild resulted with nil, so check whether the pet is in the correct place.

If this has helped, please mark this as the solution :)

0
the first one just kills me and other one doesn't work knettergek809 0 — 2y
Ad
Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

When using FindFirstChild assume that the Instance you are looking for can either exist, or not exist (nil). When doing so, check if it exists with a simple if statement and if it doesn't, then just return so nothing below in your code base runs.

Assuming "pet" is a string such as, "Pet Name", then this is how you would go about this.

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local remotes = ReplicatedStorage.Remotes

remotes.UnequipPet.OnServerEvent:Connect(function(player, pet)
    if not pet then
        return
    end

    local character = player.Character

    if not character then
        return
    end

    local foundPet = character:FindFirstChild(pet)

    if not foundPet then
        return
    end

    foundPet:Destroy()
end)
0
it doesn't give the error sign but still doesn't get the pet away knettergek809 0 — 2y
0
Is the pet argument you are passing a string like "Dog"? If so, make sure the pet name you are passing and the pet inside of the character model's name is the same. I guarantee on line 19 your code is returning OnlyRoids 20 — 2y
0
can you explain a little easier? i'm new with scripting knettergek809 0 — 2y
0
just say what i have to do knettergek809 0 — 2y

Answer this question