Ive tried to put the Mobs folder inside of workspace, it will work but it totally ruins the game. I even set the Primary parts to what it is supposed to be set to but it doesn't work. The Mobs folder is inside ServerStorage.
OUTPUT: Workspace.Tower.Towertesting:7: attempt to index nil with 'GetChildren' - Server - Towertesting:7 16:14:50.033 Stack Begin - Studio 16:14:50.033 Script 'Workspace.Tower.Towertesting', Line 7 - function FindNearestTarget - Studio - Towertesting:7 16:14:50.033 Script 'Workspace.Tower.Towertesting', Line 22 - Studio - Towertesting:22 16:14:50.033 Stack End - Studio
local Tower = script.Parent local Mobs = workspace.PrimaryPart local function FindNearestTarget() local maxDistance = 15 local nearestTarget = nil for i, target in ipairs(Mobs:GetChildren())do local distance = (target.PrimaryPart.Position - Tower.PrimaryPart.Position).Magnitude print (target.Name, distance) if distance < maxDistance then print(target.Name, "Nearest target found") nearestTarget = target maxDistance = distance end end return nearestTarget end while true do local target = FindNearestTarget() if target then target.Humanoid:TakeDamage(3) end task.wait(0.5) end
I suggest you to change the mobs' humanoids names by another thing like "HumanoidMonster" then in the loop, instead of doing GetChilder(), do workspace:GetDescendants() and the ask if the target have a humanoidmonster then your line of code
It shoould sounds like this
local Tower = script.Parent local Mobs = workspace.PrimaryPart local function FindNearestTarget() local maxDistance = 15 local nearestTarget = nil for i, target in pairs(workspace:GetDescendants()) do if target:IsA("Humanoid") and target.Name == "HumanoidMonster" then local distance = (target.Parent.PrimaryPart.Position - Tower.PrimaryPart.Position).Magnitude print (target.Parent.Name, distance) if distance < maxDistance then print(target.Parent.Name, "Nearest target found") nearestTarget = target.Parent maxDistance = distance end end end return nearestTarget end -- some parts of the scripts have been modificated. Copiable
I actually use this strategy for my basic NPCs, so I'm an expert at this.
First of all, the workspace doesn't have a primary part value, if so then probably not intended. I would use workspace.Mobs directly instead of referencing it through that value.
Plus, on top of this, I would recommend directly getting the humanoid and the root part, and returning them, not even the target itself.
Plus, you forgot some checks! I know this is completely unnecessary due to the fact that the folder (or is it a folder??) is meant for the mobs, but it's just in case.
I didn't read through this thoroughly so sorry if I misunderstand some stuff.