Search code examples
unity-game-enginegameobject

Unity: Prefab parenting in code


Let's say I want multiple prefab object called childTile, it parenting another single prefab object called parentTile. So whenever the parentTile rotates, childTiles will be rotated around parentTile.

Basically this is what I wrote:

public GameObject childPrefab;
public GameObject parentPrefab;

void Update()
{
   for(int i = 0; i < 10; i++)
   {
      GameObject clone = Instantiate(childPrefab, /*PsuedoCode: random position*/ , Quaternion.identity)

      clone.transform.parent = parentPrefab;

   }
}

The expected result is during runtime, if I rotate parentPrefab at the scene, the 10 childPrefabs should also rotate. I've tried many ways but failed, unless I manually drag childPrefabs to parentPrefab on the Hierachy bar.


Solution

  • Are you sure you want to Instantiate 10 child prefabs on each frame (Update is called once per frame).

    I think you problem is, that you did not Instantiate the parent prefab.

    If I take your code, and fix it, it works like a charm for me.

    public GameObject childPrefab;
    public GameObject parentPrefab;
    
    void Start() 
    {
        GameObject parent = Instantiate(parentPrefab) as GameObject;
    
        for(int i = 0; i < 10; i++)
        {
            GameObject child = Instantiate(childPrefab) as GameObject;
            child.transform.parent = parent.transform;
        }
    }
    

    This is the result of above code, and I suspect, that's what you want?

    enter image description here