How to change a object's parent with it's children?

Object A has a child named B. B has many children named C, D,E,F and so on. I write a script to change B’s parent to another obj named Box. When the script run, Box becomes B’s parent, but B lost its children, and they all become A’s children. How can I change B’s parents with it’s all children in the script? ,Object A has a child named B, and object b has many children named C,D,E,F…I write a script and want to change B’s parent to Another object named BOX. When the script run, BOX becomes B’s parent, but B lost it’s children, and they all become A’s children. Too wired, How to change B’s parent with it’s all children?

Here is an extension method that will do it for you. As you use unity for years, your extension method class should get pretty beefy. The amount I have is insane, but extremely useful. I just pull it into every project I use.


using UnityEngine;

/// <summary>
/// Static class for our extensions - just place somewhere in your project
/// </summary>
public static class ExtensionMethods
{
    // It's really a reverse recursive - If you moved from top down, the children of the children would be lost
    public static void SetParentRecursive(this Transform transform, Transform newParent)
    {
        for (int i = transform.childCount - 1; i >= 0; --i)
        {
            Transform child = transform.GetChild(i);
            child.SetParent(newParent);
        }
    }
}

Here is a simple test script to make sure it works. Just place it on the B object, reference the Box object, then run your game, hit space bar. (Notice how the extension method is called - just like SetParent()


using UnityEngine;


public class TestParentingScript : MonoBehaviour
{
    [SerializeField] Transform newParent;


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            transform.SetParentRecursive(newParent);
        }
    }
}

Thank you for your answer. I have already solved my problem, and the problem is C,D,E,F, which i wanna change parent are prefabs. I saw your method. Next time I’ll try to use it to change parent. Thank you, guy!