I am attempting to create an NPC module which calls a coroutine function to search for targets close to it, outside of its state machine. Though for some reason I’m not sure of, it only returns ‘true’, even when targets are detected.
function GetTarget(NPC)
return coroutine.wrap(function()
local Dist = 100
local Target = nil
local RootPart = NPC:FindFirstChild("HumanoidRootPart")
repeat wait(1)
for i,v in pairs(workspace.Characters:GetChildren())do
local Humanoid = v:FindFirstChild("Humanoid")
local TargetRoot = v:FindFirstChild("HumanoidRootPart")
if Humanoid and TargetRoot then
local Distance = (RootPart.Position - TargetRoot.Position).Magnitude
if(Distance < Dist) then
Target = TargetRoot
Dist = Distance
end
end
end
until Target
coroutine.yield(Target)
end)
end
function module:StateMachine(NPC)
local taskCoro = coroutine.create(GetTarget)
local Target = coroutine.resume(taskCoro, NPC)
while wait(1)do
print(Target)
end
end
Any ideas why?