The hierarchy goes like this. Workspace>Part>SurfaceGui>Frame> 10 Frames
What the below script is suppose to do is change the BackgroundTransparency of all of the 10 frames at once, but instead, it changes the first frame visible/insivible and then the second and third and so on. I've used pairs for a long time so this is very frustrating for me. Your guys's help is always appreciated.
while wait(0) do for _, v in pairs(workspace.Part.SurfaceGui.Frame:GetChildren()) do v.BackgroundTransparency = 1 wait(2) v.BackgroundTransparency = 0 wait(2) end end
A for
loop works on each element. Your code says to do this:
It does what you wrote.
If you want to hide them all, wait 2, then show them all, then you should say that!:
while true do for _, v in pairs(workspace.Part.SurfaceGui.Frame:GetChildren()) do v.BackgroundTransparency = 1 end wait(2) for _, v in pairs(workspace.Part.SurfaceGui.Frame:GetChildren()) do v.BackgroundTransparency = 0 end wait(2) end
A way to reduce the code-reuse and to let you do fancier things is to make a setTransparency
function.
function setTransparency(t) for _, v in pairs(workspace.Part.SurfaceGui.Frame:GetChildren()) do v.BackgroundTransparency = t end end
Your loop then simply becomes
while true do setTransparency(0) wait(2) setTransparency(1) wait(2) end
It's now even easier to do things like fading:
while true do for t = 0, 1, 0.03 do wait() setTransparency(t) end end
Coroutines are not the solution to this. They consume many resources. Coroutines are designed to compute things cooperatively. They are not designed to do two things at the same time. They make code much harder to understand, debug, and write. Don't use coroutines.
if you insist on creating coroutines to do things in parallel, you should use spawn
so that your intent is clear. Coroutines are very powerful, and if you're just creating new ones to do things in the background, you might as well save some typing as use spawn
.
That's because you're yielding in the for loop, which means it won't move on to the next task until the for loop is complete. You can avoid this problem by using a coroutine, which makes a new thread to execute the for loop in so it can resume iterating through all the frames and assign them all a function at the same time (like giving them all an invisible script).
Try and study this:
while wait() do for _,v in pairs (workspace.Part.SurfaceGui.Frame:GetChildren()) do coroutine.resume(coroutine.create(function() v.BackgroundTransparency = 1 wait(2) v.BackgroundTransparency = 0 wait(2) end)) end end
'coroutine' is a table consisting of many different functions to manipulate what a coroutine does. I don't wanna go into specific detail about how these functions work, but i recommend you study the ROBLOX wiki on them. Hope this helped!