Inverting the parent hierarchy in Unity

/
0 Comments
Here's a problem I had to solve that I couldn't find anything on Google about: turning a given parent-child hierarchy upside-down.

I had a group of GameObjects, A, B, and C. They were parented in that order, A > B > C (A was the parent of B, which was the parent of C). I wanted to turn this structure upside-down, so that it looked like C > B > A. I came up with this recursive algorithm to do it, starting with C and walking up to the highest parent:

 private void becomeParent(Transform newParent) {
     if (transform.parent == null) {
         transform.parent = newParent;
         return; // already is the parent
     }
     transform.parent.GetComponent<MyObjectScript>().becomeParent(transform);
     transform.parent = newParent;
 }


When I executed it, the parent of C would change, but the parents of B and A would remain the same. I didn't get any error messages, but it wasn't doing what I wanted. I went through some iterations with the same result. Then I realized one thing:
You aren't allowed to assign the child of a Transform to be that Transform's parent.
So when I was telling A to set its parent to be B, it couldn't do it, because B was its child.
The solution was to disconnect the parent-child relationship first (by setting the parent to null):

 private void becomeParent(Transform newParent) {  
     if (transform.parent == null) {  
         transform.parent = newParent;  
         return; // already is the parent  
     }  
     // We have to disconnect ourselves first because you can't set a child as a parent  
     GameObject currentParent = transform.parent.gameObject;  
     transform.parent = null;  
     currentParent.GetComponent<MyObjectScript>().becomeParent(transform);  
     transform.parent = newParent;  
 }  

Works like a charm!


You may also like

No comments: