- Home /
GameObject parenting during runtime
Hi, this is my very first post in unityAnswers, and I'm quite new to unity. Hope you guys can help me out.
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.
Thanks.
Answer by Xarbrough · Jun 22, 2015 at 12:46 AM
In what way does it fail? Does it not get parented in the hierarchy or does it get placed weirdly or does it not rotate the way you want?
A slightly better way to parent:
clone.transform.SetParent(parentPrefab, true);
PS: I see there are two commas in your instantiate statement. You should remove one or better remove the whole comment from within the method. Bad practice. Better define a varialbe called randomPosition/Rotation and set it to something not random with a comment saying that you will implement it later. Also there is no semicolon at the end of the line.
Your answer
Follow this Question
Related Questions
Parenting an instantiated Prefab... again 1 Answer
Make a simple tree 1 Answer
Prefabs are being overriden during runtime and destroying components is prevented? 1 Answer
Manipulate a gameobject on runtime and clone it with the current shape 0 Answers
Instantiated Object turning off scripts and audio source?(Solved) 1 Answer