Problem when parenting a transform...

I have a cube object which holds the player script. In this script I’m loading 2 prefabs and parenting their transforms to the cube transform:

    void Start () {

        GameObject player_basic = Resources.Load("Models/Knight_Rig_Animations") as GameObject;
        GameObject chest_basic = Resources.Load("Models/Knight_Chest_01") as GameObject;

        if (player_basic != null){

            player = Instantiate(player_basic);
            player.transform.parent = transform;

            //player.transform.localPosition = transform.localPosition;

            player_chest = Instantiate(chest_basic);
            player_chest.transform.parent = transform;

I want the 2 loaded prefabs to have the same position as the cube so that they will load wherever I place the cube on the terrain. However, they “spawn” far away from the cube object, and the transform pivot seems to stay at a distance “between” the cube and the 2 instantiated objects. I’ve also tried setting the prefabs localPosition to the same as the cube but it seems they instantiate on another random point, far from the parent:

How can I make these 3 objects move exactly togheter?

Either pass in the position to your Instantiate call or set your object’s localPosition to Vector3.zero after setting their parent.

Suggestions:

  • If you want to place the instantiated object precisely on the parent, you can create empty GameObjects on the parent and used them has placeholders. Then during the instantiate of the prefabs, you can used theses placeholders objects to position the prefabs.
  • For easier maintenance of your project, avoid hard-coding asset path directly in codes as string. What if the asset get reorganized into another folder or renamed?

Thanks, that did the trick!

But I had to add: “as GameObject” to the end of instantiate when specifying vector3 and Quaternion. I’m curious, why is that necessary?

@ericbegue :

My character will have many different armor/vests, so I must load them from the disk. I still haven’t found a better way of doing this, so I guess I’ll have to keep a good track of the names ^^