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)
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 :)
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)