Unity: Prefab parenting in code

Let's say I need multiple prefabs named childTile

, it brings up another prefab named parentTile

. Therefore, when it parentTile

rotates, it childTiles

will be rotated around parentTile

.

This is basically 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 runtime result is if I rotate parentPrefab

in the stage, 10 childPrefabs

should rotate as well. I've tried many ways but couldn't, unless manually drag and drop childPrefabs

in parentPrefab

the Hierachy panel.

+3


source to share


1 answer


You really want Instantiate

10 child prefabs on each frame ( Update

called once for each frame).

I think the problem is that you are not the Instantiate

parent collection.

If I take your code and fix it, it will be like a charm to 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 the above code and I suspect what you want?

enter image description here

+2


source







All Articles