You can write your topic however you want, but you need to answer these questions:
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.
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.
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
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
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.