Search Unity

Parenting of prefabs?

Discussion in 'Scripting' started by Martin-Schultz, Dec 3, 2007.

  1. Martin-Schultz

    Martin-Schultz

    Joined:
    Jan 10, 2006
    Posts:
    1,377
    Hi,

    for my little I'm-learnign-Unity project I created a bunch of different colored spheres which I instantiate at runtime. As I create lots of those, the hierachy view gets immediately flooded with all the new spheres. So basically I search for a way to group all of the new spheres into one root/parent object. If I understood the manual right, I needed to create an empty game object container which I did, but how can I now make this new gameobject the parent of the prefabs when I instantiate them from code?

    I tried searching for "parent" and "root", but didn't find appropriate stuff (or overlooked it :)

    Thanks for any help.

    Martin :)
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    What you're looking for is to set yourInstantiatedObject.transform.parent to the transform of your empty holder object.
     
  3. Martin-Schultz

    Martin-Schultz

    Joined:
    Jan 10, 2006
    Posts:
    1,377
    Ah, great, thanks. Can this be "baked" in already for the prefab or do I need to assign this when instantiating the prefab?
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    No, you have to set it in code whenever you instantiate it.
     
  5. Martin-Schultz

    Martin-Schultz

    Joined:
    Jan 10, 2006
    Posts:
    1,377
    Awesome, thanks for the quick reply. I'll give it a try tonight.
     
  6. Martin-Schultz

    Martin-Schultz

    Joined:
    Jan 10, 2006
    Posts:
    1,377
    Works super. This is how I did it:

    I created an empty GameObject called "BallContainer".

    Then I created an instance of the sphere by this line:

    clone = Instantiate(prefab1, pos, Random.rotation);

    and then fetched the BallContainer object:

    var groupParent : GameObject = GameObject.Find("BallContainer");

    and now the magic - parent the instanced sphere:

    clone.transform.parent = groupParent.transform;

    That's all. All new spheres are created as childs of the game object. :)