i’ve only just started using coroutines a lot more for multithreading. problem is that my code only runs once and stops completely after that. when i get rid of the coroutine function it works perfectly fine. i have no idea why this is happening or if im using coroutines correctly. thx!
function CustomerClass.new(customerModel)
local self = setmetatable({}, CustomerClass)
self.customerModel = customerModel
self.CustomersInLine = {}
return self
end
function CustomerClass:SpawnCustomers(CustomerSpawnPoint: CFrame)
local CustomersInLine = self.CustomersInLine
-- creates a new thread
local thread = coroutine.create(function()
while true do
local cooldown = 2
-- clearing previous customers
for _, customer in ipairs(CustomersInLine) do
if customer:IsA("Model") then
customer:Destroy()
end
end
table.clear(CustomersInLine)
local MaxCustomers = math.random(2, 6)
for c = 1, MaxCustomers do
local newCustomer = self.customerModel:Clone()
-- storing the customer in the CustomersInLine table
table.insert(CustomersInLine, newCustomer)
newCustomer:PivotTo(CustomerSpawnPoint)
newCustomer.Parent = workspace
end
print(CustomersInLine)
task.wait(cooldown)
end
end)
coroutine.resume(thread) -- starts the thread
end
Coroutine silently errored and stopped the script.
3 choices.. #1 make sure it isn’t going to errror. #2 the eye roller..
function CustomerClass:SpawnCustomers(CustomerSpawnPoint)
local CustomersInLine=self.CustomersInLine
coroutine.resume(coroutine.create(function()
while true do
for _,v in ipairs(CustomersInLine) do
if v:IsA("Model") then v:Destroy() end
end
table.clear(CustomersInLine)
for i=1,math.random(2,6) do
local c=self.customerModel:Clone()
table.insert(CustomersInLine,c)
c:PivotTo(CustomerSpawnPoint)
c.Parent=workspace
end
print(#CustomersInLine)
task.wait(2)
end
end))
end
#3 The one you should be using for this..
function CustomerClass:SpawnCustomers(CustomerSpawnPoint)
task.spawn(function()
local CustomersInLine=self.CustomersInLine
while true do
for _,v in ipairs(CustomersInLine) do
if v:IsA("Model") then v:Destroy() end
end
table.clear(CustomersInLine)
for i=1,math.random(2,6) do
local c=self.customerModel:Clone()
table.insert(CustomersInLine,c)
c:PivotTo(CustomerSpawnPoint)
c.Parent=workspace
end
print(#CustomersInLine)
task.wait(2)
end
end)
end
Use task.spawn for long-running independent loops. Use coroutines only when you need manual yield/resume control.