Closest HumanoidRootPart Targeting System Misses Entity

Hello,

I’ve been working on a sort of tower defense game and I’ve run into some problems regarding how the towers interact with the enemies.

– Extra info –
For anyone who doesn’t know a tower defense game is a game which consists of a group of enemies who must make their way to the end of a course. The player can use units a.k.a. towers which fight the enemies to stop them from reaching the end.

– Main problem –
I designed a simple system which should target the enemy closest to the tower but theres an odd problem where it wont target the final enemy to appear in its range. I’ve boiled it down to some sort of problem in the function which targets the enemies. I have an idea of what might fix it but before I start re-writing the function I was wondering if there is an easier way so i’m consulting the dev forums.

As a sidenote this script is an edited version of a script I took from this video which I used for a seperate project.

I’m sure theres just some small (or large) overlooked problem with the script that I either don’t understand or just missed. If anybody could find it that would help so much because I could start working on other aspects of the game as I am currently worrying about this issue.

– Code –

function gethumanoids()
	if workspace.Course.Enemies:GetChildren()[1] then
		local humanoidpos = {}

		for i,x in pairs (workspace.Course.Enemies:GetChildren()) do
			if x:FindFirstChild("HumanoidRootPart") and x ~= script.Parent then
				table.insert(humanoidpos,(script.Parent.HumanoidRootPart.Position - x.HumanoidRootPart.Position).magnitude)

			end
		end

		table.sort(humanoidpos)

		for i,x in pairs(humanoidpos) do
			if x ~= 1 then
				table.remove(humanoidpos,i)
			end
		end
		for i,x in pairs (workspace.Course.Enemies:GetChildren()) do
			if x:FindFirstChild("HumanoidRootPart") and x ~= script.Parent then
				if (script.Parent.HumanoidRootPart.Position - x.HumanoidRootPart.Position).magnitude == humanoidpos[1] then
					return x
				end
			end
		end
	else
		return nil
	end
end

Figured out there is something else wrong with the script after posting this. It was working fine yesterday but it had oddly broken even in the older versions of the project.

edit: Fixed but it still misses an enemy

Your current method of finding the nearest enemies will only find stationary target.

I sent it to a friend of mine and he fixed it. The issue was that all for i,x in pairs has to be changed to for _,x in pairs

Changing the name of the variable won’t do anything…

It did though. I dont know how it worked but it did.