Help with implementing spawn, or coroutine

  1. 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

Thank you.

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
1 Like

if you are going to be using spawn()
then use task.defer() instead

1 Like

Made that edit. I’ve been inactive for a while and haven’t even heard of the task library lol.

Thank you so much for your time!

Here’s a quick cheat-sheet which covers when to use which method: Task Library - Now Available! - #172 by WallsAreForClimbing

2 Likes

Nice, thanks. I will make sure to replace my waits and spawns with that. Thanks for the tip.