Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I make multiple functions run simultaneously from the same script?

Asked by
Trew86 175
5 years ago

I tried making this function to a coroutine but...

module.Functions.Dispatch = coroutine.wrap(function(train, path, button)
    if path == nil then return end
    button.Text = path.Name
    while wait() do
        if path.Status == 0 then
            button.TextColor3 = Color3.new(0, 170, 0)
            button.Active = true
        elseif path.Status == 1 then
            button.TextColor3 = Color3.new(255, 255, 0)
            button.Active = true
        elseif path.Status == 2 then
            button.TextColor3 = Color3.new(255, 0, 0)
            button.Active = false
        end
        if train == nil then
            button.Text = ""
            button.Active = false
            break
        end
    end
end)

when I call it multiple times, only the first one starts.

module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[1], O1)
module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[2], O2)
module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[3], O3)

How can I run them at the same time? Thanks.

0
Only one coroutine ever runs at a time theking48989987 2147 — 5y

1 answer

Log in to vote
1
Answered by
sleazel 1287 Moderation Voter
5 years ago
Edited 5 years ago

Use spawn. I would avoid coroutine, unless you require some specific coroutine functionality.

spawn(module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[1], O1))
spawn(module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[2], O2))
spawn(module.Functions.Dispatch(mod.QueuedTrain, mod.Paths[3], O3))

Edit: If you want spawn inside function, you can do it like this:

module.Functions.Dispatch = function(train, path, button)
    if path == nil then return end
    button.Text = path.Name
    spawn(function()
        while wait() do
            if path.Status == 0 then
                button.TextColor3 = Color3.new(0, 170, 0)
                button.Active = true
            elseif path.Status == 1 then
                button.TextColor3 = Color3.new(255, 255, 0)
                button.Active = true
            elseif path.Status == 2 then
                button.TextColor3 = Color3.new(255, 0, 0)
                button.Active = false
            end
            if train == nil then
                button.Text = ""
                button.Active = false
                break
            end
        end
    end)
end
Ad

Answer this question