Hi, my intent is to have the while loop run every 2 seconds, not wait for the code inside the while loop to be complete to run again; which it currently does. I believe this can be solved with the use of coroutine, or spawn to make the loop run independently, however, I’m unfamiliar with how I’d implement that.
-- NPC Spawner
local chars = game.ServerStorage.Characters
local spawns = game.Workspace.Locations
while wait(2) do
local charsTable = chars:GetChildren()
local rndmChar = charsTable[math.random(1, #charsTable)]
local spawnTable = spawns:GetChildren()
local rndmSpawn = spawnTable[math.random(1, #spawnTable)]
local spawnLoc = rndmSpawn:FindFirstChild("spawnLocation").Position
local walkTo = rndmSpawn:FindFirstChild("walkToLocation").Position
local charClone = rndmChar:Clone()
charClone:SetPrimaryPartCFrame(CFrame.new(spawnLoc + Vector3.new(0,5,0)))
charClone.Parent = workspace.SpawnedNPCs
charClone.Humanoid:MoveTo(walkTo)
charClone.Humanoid.MoveToFinished:Wait()
charClone.Humanoid:MoveTo(spawnLoc)
charClone.Humanoid.MoveToFinished:Wait()
end
If I’m understanding correctly, you want the code to run every two seconds, even if the code takes more than two seconds to complete.
You are correct, you would need to use code threading to complete this.
Although some developers would probably suggest to use coroutine instead of spawn, here is your script implementing the spawn function (less complex than coroutine).
-- NPC Spawner
local chars = game.ServerStorage.Characters
local spawns = game.Workspace.Locations
while wait(2) do
task.defer(function()
local charsTable = chars:GetChildren()
local rndmChar = charsTable[math.random(1, #charsTable)]
local spawnTable = spawns:GetChildren()
local rndmSpawn = spawnTable[math.random(1, #spawnTable)]
local spawnLoc = rndmSpawn:FindFirstChild("spawnLocation").Position
local walkTo = rndmSpawn:FindFirstChild("walkToLocation").Position
local charClone = rndmChar:Clone()
charClone:SetPrimaryPartCFrame(CFrame.new(spawnLoc + Vector3.new(0,5,0)))
charClone.Parent = workspace.SpawnedNPCs
charClone.Humanoid:MoveTo(walkTo)
charClone.Humanoid.MoveToFinished:Wait()
charClone.Humanoid:MoveTo(spawnLoc)
charClone.Humanoid.MoveToFinished:Wait()
end)
end