Attempt to index nil with 'Destroy'

game.ReplicatedStorage.EggHatchingRemotes.UnequipPet.OnServerInvoke = function(player, petName)
	workspace.Player_Pets:FindFirstChild(player.Name):FindFirstChild(petName):Destroy()

This outputs: attempt to index nil with ‘Destroy’
What’s wrong?

have you tried using

:WaitForChild()

instead of

:FindFirstChild

It may have not loaded in yet

Attempt to index nil means your telling your code to destroy nothing, as in your code didnt find any object to destroy

hey, so the error happens because you see :FindFirstChild just gets the part immediately, i reccomend using :WaitForChild("") because it waits for it to “Load” then it does the action

Because you’re using :FindFirstChild(), there won’t be an error if the object you’re trying to find doesn’t exist. Instead, it returns nil.

In most scenarios, this is actually a good thing. It lets us handle both cases manually without dealing with errors.

local playerPets = Player_Pets:FindFirstChild(player.Name)

if playerPets then
	local pet = playerPets:FindFirstChild(petName)
	
	if pet then
		pet:Destroy()
	else
		warn("Couldn't find the pet!")
	end
else
	warn("Couldn't find the players pet folder!")
end

If you’re sure that the directory exists (or should exist) then you might want to look into using :WaitForChild(). This works in a similar fashion to FindFirstChild() although it yields your script until the object exists.

local playerPets = Player_Pets:WaitForChild(player.Name)
print("Found player pet folder!")

Hope this helps :slight_smile: