I am making a NPC system, but I am having one problem wich is that you have to wait till the function finishes to start another function. With coroutine.wrap()
it returns an error where it’s saying that its missing a function.
Here is my module Code:
local ServerStorage = game:GetService("ServerStorage")
local Physics = game:GetService("PhysicsService")
local Players = game:GetService("Players")
local Nodes = workspace.Nodes
local MainNodes = Nodes.Main
local OtherNodes = Nodes.Other
local SpawnNodes = Nodes.Spawns
local NPCTemplate = ServerStorage.Dummy
local NPCModule = {}
NPCModule.__index = {}
function NPCModule.SpawnNPC()
local NewNPC = {}
setmetatable(NewNPC, NPCModule)
NewNPC.NPCClone = NPCTemplate:Clone()
local Choose = math.random(1, #SpawnNodes:GetChildren())
local ChoosenSpawn = SpawnNodes:GetChildren()[Choose]
--Setting Collision
for _, v in ipairs(NewNPC.NPCClone:GetChildren()) do
if v:IsA("BasePart") or v:IsA("MeshPart") then
Physics:SetPartCollisionGroup(v, "NPC")
end
end
NewNPC.NPCClone:FindFirstChild("HumanoidRootPart").CFrame = ChoosenSpawn.CFrame
NewNPC.NPCClone.Parent = workspace.NPCs
return NewNPC
end
function NPCModule:NPCMoveTo(Target : Vector3, HumanoidRootPart, Humanoid)
if not Humanoid then return warn("There is no Humanoid", Humanoid) end
if not HumanoidRootPart then return warn("There is no HumanoidRootPart", HumanoidRootPart) end
repeat
task.wait()
Humanoid:MoveTo(Target)
until (HumanoidRootPart.Position - Vector3.new(Target.X, HumanoidRootPart.Position.Y, Target.Z) ).Magnitude <= 1
end
function NPCModule:ManageNPC(NPC)
print(self)
local Humanoid = self:FindFirstChild("Humanoid")
local HumanoidRootPart = self:FindFirstChild("HumanoidRootPart")
NPCModule:NPCMoveTo(OtherNodes.Entrance.Position, HumanoidRootPart, Humanoid)
local NodeAmmount = math.random(1, #MainNodes:GetChildren())
for Count = 1, NodeAmmount do
NPCModule:NPCMoveTo(MainNodes[math.random(1, #MainNodes:GetChildren() ) ].Position, HumanoidRootPart, Humanoid)
task.wait(math.random(0, 15))
end
end
return NPCModule
And here is my server script code:
while true do
task.wait(3)
local NPC = NPCModule.SpawnNPC()
spawn(NPCModule.ManageNPC(NPC.NPCClone))
end