Search Unity

How to dynamically create EmptyObject as child via Script

Discussion in 'Scripting' started by shinriyo_twitter, Nov 11, 2011.

  1. shinriyo_twitter

    shinriyo_twitter

    Joined:
    Aug 12, 2011
    Posts:
    328
    Hello there

    I'd like to attach EmptyObject which attached collider.

    Describing English is difficult for me, so I describe my image via program.

    In the Hierarchy, there are Parent GameObject.

    C# program attached Parent
    Code (csharp):
    1.  
    2. void Start () {
    3.         Game child = gameObject.AddChildEmptyObject(); // it doesn't exist. i want the method.
    4.         child.AddComponent("BoxCollider");
    5. }
    6.  
    7.  
     
  2. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    868
    Code (csharp):
    1.  
    2. void Start(){
    3.         Game child = new GameObject(); // create a new object
    4.         child.AddComponent("BoxCollider");
    5.         child.transform.parent = transform; //will set the new object to be a child of our gameObject's transform
    6. }
    7.  
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    No need for AddComponent here:

    Code (csharp):
    1. GameObject child = new GameObject("Empty", typeof(BoxCollider));
    --Eric
     
  4. shinriyo_twitter

    shinriyo_twitter

    Joined:
    Aug 12, 2011
    Posts:
    328
    Hi FlamingHairball

    Thanks for 5 minutes reply!
    Game was typo, but I understood. so, no problem.

    before your reply I found CreatePrimitive but "PrimitiveType" didn't have "Empty" ;P
    your new GameObject(); is best!
    Code (csharp):
    1.  
    2. GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    3.  
     
  5. shinriyo_twitter

    shinriyo_twitter

    Joined:
    Aug 12, 2011
    Posts:
    328
    Hi Eric5h5

    Thanks for telling me cool scripting!
    I'm loving such as GameObject's cool constructor!