Repeating function after table.remove

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I’m trying to create a system that detects when an enemy enters a unit’s range, adding it to a table when it does, and removing it when it leaves said unit’s range.

  2. What is the issue? Include screenshots / videos if possible!
    While the code works as intended, it continues trying to remove the instance after it has exited the range.
    bug

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried adding a break function in the code, but that didn’t work either.

local tower = script.Parent
local humRoot = tower.HumanoidRootPart
local DetRad = tower.DetectionRadius
local Enemies = {}
while wait() do
	for _,v in pairs(game.Workspace:GetChildren()) do
		if v:FindFirstChild("Enemy") then
			if (v.Position - humRoot.Position).Magnitude <= DetRad.Value and not table.find(Enemies,v)  then
				table.insert(Enemies,v)				
				print(v.Name .. " inserted into table 'Enemies'")
			elseif (v.Position - humRoot.Position).Magnitude > DetRad.Value and table.find(Enemies,v) then				
				table.remove(Enemies,_)
				print(v.Name .. " removed from table 'Enemies'")
				break
			end
		end
	end
end

I would suggest using GetPartBoundsInRadius instead, for more accurate results.

First of all, “_” in for loops is used to indicate an index which isn’t used (when in your case it is, consider changing it to “i” or “index” to represent as such). Secondly, table.remove() returns the value of the removed entry/element (if one was removed, otherwise it’ll return nil).

local enemy = table.remove(Enemies,_)
if enemy then
	print(enemy .. " removed from table 'Enemies'")
end
1 Like

I used this, and it doesn’t print out the message.
I don’t receive any error messages though.

That means table.remove() isn’t removing any elements from the table, you can verify this by doing print(enemy) before if enemy then, nil will be printed.

It does print nil, but I still don’t know where the error is originating from since no message is printed in the output

There is no error, table.remove() is just not removing anything from the table as previously stated.

Instead of using _ in your for loop, use something like i. Replace the rest of the code as necessary.

table.remove causes a left-shift in the array. You will end up skipping indices or removing the wrong enemy altogether.