Attempt to call missing method 'Destroy' of table (Error)

For my game, I needed a script for making enemies spawn after entering an area, but before spawning the enemies, the previous enemies in the map needed to be removed to reduce lag.

Therefore, I have made a OnTouched script for detecting if there is children inside the global enemy folder, getting and destroying said children if they exist, and then cloning the folder containing the enemies to parent them to the global enemy folder.

I, however, had an issue that rendered the entire script non-functional. The script wasn’t working so I checked the output and noticed that everytime I touched the part that was parent to the script, I would get a line on the output saying "Workspace.Spawn7B.Script:9: attempt to call missing method ‘Destroy’ of table ".

I have tried implementing a simple debounce but it broke the script entirely; not only did I not get the error, but nothing would even happen upon touching the parent part. Other than that, I don’t really know what to do. My searches for similar issues have availed me nothing.

Here is the script:

local enemies = workspace.Enemies

function onTouched(part)
	if part.Parent:findFirstChild("Humanoid")~=nil then -- check if humanoid exists (works)
		if game.Workspace.Enemies:GetChildren()~=nil then -- check if there are instances inside the enemies folder (possible cause)
			local oldenemies = workspace.Enemies:GetChildren()
			oldenemies:Destroy()
		end
		local enemies = game.ServerStorage.Enemies.F2:Clone()
		enemies.Parent = workspace.Enemies
		wait(1)
	end
end

script.Parent.Touched:connect(onTouched)

I have the feeling that the root of the problem is GetChildren(), but I do not know how else I may get and destroy the instances inside the enemy folder.

GetChildren returns a table, not a direct Instance. To the VM, you’re trying to do this:

({Instance...}):Destroy() -- The VM will try to find a property named 'Destroy' attached to the table

Instead, you’d want to do a loop, and call Destroy on each Instance:

for _, object in oldenemies do
   object:Destroy() -- Calls destroy on each Instance in the table
end

Alternatively, you can also call ClearAllChildren which does the same thing:

workspace.Enemies:ClearAllChildren()

This also won’t work the way you think. GetChildren will always return a table, even if there’s nothing in it. You’d want to check if the table is empty:

-- '#' is the length operator
-- it returns the length of a string or an array
if #workspace.Enemies:GetChildren() > 0 then
1 Like

You are completely right. My mistake was utilizing GetChildren in order to “select” the children and then remove them, but now I know that it doesn’t work that way. I instead used ClearAllChildren, and that resulted in the rest of the code working just as intended. Thank you so much!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.