-1

I've got some objects, one called "Parent", 3 called "Child" (Nr. 1 in the picture). How can I make, at runtime, the "Child" objects be actual children of the "Parent" object (Nr. 2 in the picture)?

image

1
  • 2
    transform.setParent(parentObject); Jan 9, 2017 at 15:40

2 Answers 2

5

Something like this should works:

public GameObject Parent;
public List<GameObject> Childs;

public void SetParent(){
    foreach(var child in Childs){
        child.transform.SetParent(Parent, false);
    }
}

Edit: The second parameter of SetParent tells Unity to keep the world's parameters of your object:

worldPositionStays: If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

1
  • I feel the need to point that false in SetParent(...) is crucial ;). If you care about the order of your child objects, use: child.transform.SetAsLastSibling(); Jan 9, 2017 at 15:06
2

One of many ways is:

create a class to hold an arbitrary number of Child objects.

public class Children: List<Child> {}

then, add a property to the Parent class of that type

public class Parent
{
    public Children Children { get; set; }

}

then just add the 3 Child objects to the Children Property

var p = new Parent();
p.Children = new Children();
p.Children.Add(new Child());
p.Children.Add(new Child());
p.Children.Add(new Child());

access the Child objects just like you would any other property

var child1 = p.Children[0];
var child2 = p.Children[1];
var child3 = p.Children[2];

or

foreach( var c in p.Children)
   //.... do something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.