I am trying to make a medic NPC that will heal the nearest friendly, and if there is none damaged, instead follow a radius around the nearest player.
The code works fine, until after it heals a target. After which, it will start repeating the closestFriendlyHrp check without actually finding one, even though the function is indeed returning nil which should activate the elseif not closestFriendlyHrp statement which would remove it from the loop, yet it doesn’t.
The code:
while wait(4) and hum.Health > 0 do
warn("beginning")
local closestFriendlyHrp = findClosestDamagedPolicesHrp(hrp, 200)
print("friendly hrp check")
if closestFriendlyHrp then
print("friendly hrp found")
while wait(1) and closestFriendlyHrp ~= nil and closestFriendlyHrp.Parent and closestFriendlyHrp.Parent.Humanoid.Health > 1 and (hrp.Position - closestFriendlyHrp.Position).Magnitude < 200 do
print("chrpcheck")
hum:MoveTo(closestFriendlyHrp.Position, closestFriendlyHrp)
if (hrp.Position - closestFriendlyHrp.Position).Magnitude < 5 and CanHeal and --[[math.random(0, 2) ~= 0 and]] closestFriendlyHrp.Parent.Humanoid.Health ~= closestFriendlyHrp.Parent.Humanoid.MaxHealth then
print("chrptarg")
print("medic is healing target: " .. closestFriendlyHrp.Parent.Name)
CanHeal = false
closestFriendlyHrp.Parent.Humanoid.Health += closestFriendlyHrp.Parent.Humanoid.Health / 3
hum:MoveTo(hrp.Position, hrp)
wait(4)
CanHeal = true
end
end
elseif not closestFriendlyHrp then
print("not")
local closestHrp = findClosestPlayersHrp(hrp, 400)
print("plr check")
if closestHrp then
print("plr")
while closestHrp.Parent and closestHrp.Parent.Humanoid.Health > 1 and (hrp.Position - closestHrp.Position).Magnitude > 42 do
hum:MoveTo(closestHrp.Position, closestHrp)
wait(1)
end
hum:MoveTo(hrp.Position, hrp)
end
end
end
Any help would be much appreciated!