Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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

1 comment

0

the first one just kills me and other one doesn't work

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)

4 comments

0

it doesn't give the error sign but still doesn't get the pet away

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

0

can you explain a little easier? i'm new with scripting

0

just say what i have to do

This discussion is preserved as it was. New answers, comments, and votes are closed.