How to change the parent of instances in a for loop

I noticed that if you change the parent of a model being the subject of an iteration, the for loop breaks. Here’s an example:

for i, v in pairs (models) do --assume there are five models
print(i)
v.Parent = workspace
end

This for loop would only print once due to the interruption.

How would I get around this?

1 Like

It shouldn’t be. Can I see your actual code so I can see how you’re initializing models? Maybe a bit more code for context? Maybe a bit more code for context? Are you saying that when you don’t run the v.parent code, it runs normally? Where is this script located?

for i, v in ipairs (game.ServerStorage:FindFirstChild(script:GetAttribute("TargetModuleFolder")):GetChildren()) do
v.Parent = workspace
task.wait()
v.Parent = game.ServerStorage:FindFirstChild(script:GetAttribute("TargetModuleFolder"))
end

Yes, it runs normally if the parent defining lines are removed. Apologies for the lack of context.

Don’t think it would, but does putting it in a variable have any effect?

local initialParent = game.ServerStorage:FindFirstChild(script:GetAttribute("TargetModuleFolder"))
local children = initialParent:GetChildren())

for i, v in ipairs(children) do
    print(i)
    v.Parent = workspace
    task.wait()
    v.Parent = initialParent
end

I did what you suggested, it only printed once. While I was awaiting a reply I tried to find a work around by looping without pairs (for i = 1,10) and serialized the instances so I could access them via variable, it still broke when I changed the parent, how bizzare!

try it with a breakpoint and see what happens maybe. not quite sure what could be causing it.

try pairs as well instead of ipairs

So I figured out it only happens when I try to move a model to the workspace. Moving it anywhere else still works

Ah, now I am beginning to understand why you guys want the code. It ended up being a rouge infinite yield loop in a function that I thought was irrelevant. Apologies for the inconvenience.

1 Like

Nope, glad you figured it out!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.