Unity 6.3
0 онлайн 85 гостей 3 в системе
Вход

Transform.DetachChildren

Declaration

public void DetachChildren();

Описание

Отключить родительские права всех дочерей целевого объекта.

Каждый непосредственный дочерний объект перемещается на корневой уровень с сохранением своей внутренней иерархии. Это удобно, когда нужно уничтожить корень иерархии, не уничтожая потомков, и работает эффективнее, чем отсоединение каждого потомка по отдельности.

Дополнительные ресурсы: Transform.parent чтобы отделить/изменить родитель одного преобразования.

                        {
    GameObject root = new GameObject("Root");
    AddChildTransforms(root.transform, new[] { "Child1", "Child2", "Child3" });
    // Destroying an object destroys its children as well. To avoid this,
    // the children must first be detached. We can't safely detach children
    // while iterating through its child list, so we need to extract them into
    // a separate list as a pre-pass.
    List<Transform> children = new List<Transform>();
    for(int i=0; i<root.transform.childCount; ++i)
    {
        children.Add(root.transform.GetChild(i));
    }
    // Now we can safely deparent each child.
    foreach (Transform child in children)
    {
        child.SetParent(null, true);
    }
    Assert.AreEqual(0, root.transform.childCount);
    // Destroying the root no longer destroys the children
    Object.Destroy(root.gameObject);
}

{
    GameObject root = new GameObject("Root");
    AddChildTransforms(root.transform, new[] { "Child1", "Child2", "Child3" });
    // This has the same effect as the above loops.
    root.transform.DetachChildren();
    Assert.AreEqual(0, root.transform.childCount);
    // Destroying the root no longer destroys the children
    Object.Destroy(root.gameObject);
}