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

attempt to index nil with 'GetChildren' ?

I am trying to create a simple script inside of an NPC, where when it dies the pieces will disappear after 3 seconds. However i am getting the error attempt to index nil with 'GetChildren' in my script and i can't figure it out:

local function dead()
	wait(3)
	for i,v in pairs(script.Parent:GetChildren()) do
		v:Destroy()
	end  
	
end
humanoid.Died:Connect(dead)

The script is inside of the NPC, so the parent would be the model. There is no reason (that i know of) that it should be nil. Any help is appreciated!!!

1 answer

You haven't specified if you have used a LocalScript or a ServerScript. I can't seem to see any issues with the script you have provided, assuming that it's just a snippet of the code, otherwise you are missing the Humanoid Variable.

You should be using a ServerScript to achieve this.

See if this works for you:

local NPC = script.Parent
local Humanoid = NPC.Humanoid

local function DespawnNPC()
	wait(3)
	for _, CharacterPart in pairs(NPC:GetChildren()) do
		CharacterPart:Destroy()
	end
end

Humanoid.Died:Connect(DespawnNPC)

Hope this helps

1 comment

0

To add on to this, by destroying everything under the Model, you're leaving the empty model in the workspace. Why not just call script.Parent:Destroy()?

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