- Home /
Trying to child multiple GameObjects to one master object in script
So what I'm doing is creating a empty GameObject at runtime, caching a bunch of already created GameObjects, and I'm trying to "move" all these GameObjects into the new empty GameObject I create at runtime. Here's my code below:
public class ReloadTrack : MonoBehaviour {
// Define variables...
private GameObject duplicateTrack;
private GameObject duplicateAll;
void Start () {
duplicateTrack = GameObject.Find ("TestPieces");
duplicateAll = new GameObject ("duplicateAll");
duplicateAll.gameObject.AddComponent<duplicateTrack>();
}
}
Obviously the above code isn't working. I can't figure out out to add my GameObjects to the empty GO...
Answer by yoyo · Jan 07, 2011 at 05:36 AM
duplicateTrack is a game object, not a component. To move it under duplicateAll, you need to parent it's transform, like so:
duplicateTrack.transform.parent = duplicateAll.transform;
Note that the hierarchy is all in the relationships between transforms, not the objects themselves. Also note that when you reparent an object, it keeps the same world position, but gets a new local position (relative to its new parent).
Thanks for your answer yoyo...it makes a lot more sense now!