I want to be able to have all objects that are not parented to this one, to automatically parent themselves with it.
Thanks.
You always have to be carefully with words like “all”. Do you talk about all objects that don’t have a parent at all? If so, keep in mind to exclude the one that is your parent. There has to be at least one object without a parent (so the parent is the scene).
Basically you just would retrieve a list to all objects and search for those without a parent. Working with hierarchies and changing parents in a loop can cause many issues. So i would first create a list of all objects and finally set the parent.
import System.Collections.Generic;
function ParentEverythingTo(newParent : Transform)
{
var parentRoot = newParent.root;
var transforms = FindObjectsOfType(Transform);
var withoutParent = new List.<Transform>();
for(var T : Transform in transforms)
{
var root = T.root;
if (root != parentRoot && !withoutParent.Contains(root))
withoutParent.Add(root);
}
for(var T : Transform in withoutParent)
{
T.parent = newParent;
}
}
This will grab all topmost objects (which doesn’t have a parent) and add them to the list unless they are already in the list. The most important thing is to ignore the object you want to use as parent.
Tested and works
edit
Just thought about it one more time and i guess it should also work this way
function ParentEverythingTo(newParent : Transform)
{
var parentRoot = newParent.root;
var transforms = FindObjectsOfType(Transform);
for(var T : Transform in transforms)
{
var root = T.root;
if (root != parentRoot)
root.parent = newParent;
}
}