Hello, i am creating a script where when the humanoid is damaged, it walks to the closest player in range. But it isn't working, when everything is correct and where it should walk.
Script:
local runService = game:GetService("RunService")
local oldHealth = 75
local range = 40
local targetFollow
local initiate = 0
script.Parent.Enemy.Changed:Connect(function(plays)
local hum = script.Parent.Enemy
print(1)
if hum.Health < oldHealth then
print(2)
oldHealth = hum.Health
local target
local mag = math.huge
for i, v in pairs(game.Players:GetPlayers()) do
local magnitude = (script.Parent.HumanoidRootPart.Position - v.Character.HumanoidRootPart.Position).Magnitude
if magnitude < mag then
mag = magnitude
target = v.Character
end
end
if target ~= nil then
print(3)
if mag < range then
targetFollow = target
initiate = initiate + 1
print(4)
else
targetFollow = nil
end
else
targetFollow = nil
end
else
oldHealth = hum.Health
end
end)
local oldInitate = 0
runService.Stepped:Connect(function(plays)
if targetFollow ~= nil then
if oldInitate ~= initiate then
local magnitude = (script.Parent.HumanoidRootPart.Position - targetFollow.HumanoidRootPart.Position).Magnitude
if magnitude < range then
script.Parent.Enemy:MoveTo(targetFollow.HumanoidRootPart.Position, targetFollow.HumanoidRootPart)
initiate = oldInitate
print("e")
else
targetFollow = nil
end
end
end
end)
script.Parent.Enemy:MoveTo(targetFollow.HumanoidRootPart.Position, targetFollow.HumanoidRootPart) is the important line
targetFollow is my player, wont work. Please help
