I am very confused with what is the error of this code.
I tried several changes but the model still stands in place.
local Badguy = script.Parent
local maxdistance = 15
local BestDistance = 15
local targeted = nil
local Players = game:GetService("Players")
i = true
local function FindNearestTarget()
for i, target in ipairs(workspace:GetChildren()) do
local pro = false
local player = nil
if target:FindFirstChild("Humanoid") then
player = Players:FindFirstChild(target.name)
if player then
local distance = (target.PrimaryPart.Position - Badguy.PrimaryPart.Position).Magnitude
if distance < BestDistance and distance < maxdistance then
targeted = target
BestDistance = distance
end
end
end
end
return targeted
end
while true do
local target = FindNearestTarget()
if target then
print(target)
if target:FindFirstChild("PrimaryPart") then
print(target:FindFirstChild("PrimaryPart"))
local targetPosition = target.PrimaryPart
Badguy.Humanoid:MoveTo(targetPosition.Position, target)
end
end
task.wait(1)
end
Ok SO i found your issue, you are trying to find PrimaryPart inside the Character which doesn’t exist and is only a Property of the Model that is the character
local Badguy = script.Parent
local maxdistance = 15
local BestDistance = 15
local targeted = nil
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
i = true
local function FindNearestTarget()
for i, target in ipairs(workspace:GetChildren()) do
local pro = false
local player = nil
if target:FindFirstChild("Humanoid") then
player = Players:FindFirstChild(target.name)
if player then
local distance = (Badguy.PrimaryPart.Position- target.PrimaryPart.Position).Magnitude
if distance < BestDistance and distance < maxdistance then
targeted = target
BestDistance = distance
end
end
end
end
return targeted
end
while true do
RunService.Heartbeat:Wait()
local target = FindNearestTarget()
if target then
print(target)
if target.PrimaryPart ~= nil then
print(target.PrimaryPart)
local targetPosition = target.PrimaryPart
Badguy.Humanoid:MoveTo(targetPosition.Position)
end
end
end
Badguy.HumanoidRootPart:SetNetworkOwner(nil)