I recently wrote a script and due to my unfamiliarity with coroutine I don’t really understand why something is happening.
When I run this script it plays once and stops, but I need it to continue infinitely. I am not using a while true loop as it needs to continue and go through all the children. I am sure I am missing something super obvious lol, any help appreciated
local Model = script.Parent
local tweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(2, Enum.EasingStyle.Cubic)
local colour1 = {Color = Color3.new(0,0,1)}
local colour2 = {Color = Color3.new(0.1, 0.6, 1)}
local colour3 = {Color = Color3.new(0,0,1)}
for _, child in ipairs(Model:GetChildren()) do
local tween1 = tweenService:Create(child, tweenInfo, colour1)
local tween2 = tweenService:Create(child, tweenInfo, colour2)
local tween3 = tweenService:Create(child, tweenInfo, colour3)
local function colourChange()
tween1:Play()
tween1.Completed:Wait()
tween2:Play()
tween2.Completed:Wait()
tween3:Play()
tween3.Completed:Wait()
end
local colourWrap = coroutine.wrap(colourChange)
colourWrap()
end
Also I know that colour3 is unnecessary; I built a modular script and just used it to extend colour1 in this scenario as I don’t want to modify the base script overly much until I get it working
When using coroutine, it essentially runs in the background, Usually for Multi Tasking,
for example, when the coroutine is running, the script will ignore it and move on to the rest of the script.
But when the coroutine is finished, it is considered dead to the script and will never be used again until another one is created.
To prevent this, Add a Loop:
local colourWrap = coroutine.wrap(function()
while task.wait() do
-- Your Code here
end
end)
colourWrap() -- calls the coroutine
However if you are only doing One Task, then the coroutine is useless to add
This will probably better suit you than a coroutine if you are trying to make it loop infinitely
local Model = script.Parent
local tweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(2, Enum.EasingStyle.Cubic)
local colour1 = {Color = Color3.new(0,0,1)}
local colour2 = {Color = Color3.new(0.1, 0.6, 1)}
local colour3 = {Color = Color3.new(0,0,1)}
for _, child in ipairs(Model:GetChildren()) do
local tween1 = tweenService:Create(child, tweenInfo, colour1)
local tween2 = tweenService:Create(child, tweenInfo, colour2)
local tween3 = tweenService:Create(child, tweenInfo, colour3)
tween1:Play()
tween1.Completed:Connect(function()
tween2:Play()
end)
tween2.Completed:Connect(function()
tween3:Play()
end)
tween3.Completed:Connect(function()
tween1:Play()
end)
end