Tower Attack issue

Hi! I’m currently working on a tds game and have run into an issue with towers attacking. Here is my script:

local tower = script.Parent
local mobs = workspace.Mobs

local maxdistance = 50
local nearesttarget = nil

local function findnearesttarget()
	for i, target in ipairs(mobs:GetChildren()) do
		local distance = (target.HumanoidRootPart.Position - tower.Position).Magnitude
		print(target.Name, distance)
		if distance < maxdistance then
			print(target.Name, "is the nearest target found so far")
			nearesttarget = target
			maxdistance = distance
		end
	end
	
	return nearesttarget
end

while true do
	local target = findnearesttarget()
	if target then
		target.Humanoid:TakeDamage(25)
	end
	wait(1)
end

For some reason at some random time, the tower just stops killing them leaving this error:
Humanoid is not a valid member of model "target"

It kills like 2 monsters then just quits. Anyone have any idea at all what’s going on?? I’m following a tutorial and it’s not happening for him. Thanks.

1 Like

try this :

while true do
	local target = findnearesttarget()
	if target then
		if target:FindFirstChild("Humanoid") then
			target.Humanoid:TakeDamage(25)
		end

		
	end
	wait(1)
end
1 Like

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