- Home /
Why does Instantiate not reset childs positions in a prefab?
There is something I do not understand about the way how Instantiate works. I uploaded an example project to show the problem.
There is a prefab which exists out of these objects: Container (container holding 2 rigidbody2d child objects) -Rigidbody1(2D Cube rigidbody) -Rigidbody2(2D Cube rigidbody)
When I first run the game with the container object at 0,7,0 the cubes are childed at the same position. But when I instantiate the prefab during runtime say at position 0,7,0. Then the Container object indeed gets cloned to that position, however the child rigidbody objects gets the exact same position as the child objects from the object "container" who calls the instantiate. The container object has this code (the prefab variable has itself as prefab from the project hierarchy)
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
public GameObject prefab;
public static bool coolDown = false;
IEnumerator CoolDown() {
coolDown = true;
yield return new WaitForSeconds (3);
coolDown = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space) && !coolDown) {
Instantiate(prefab, new Vector3(0,7,0), Quaternion.identity);
StartCoroutine("CoolDown");
}
}
}
How can I instantiate the prefab with child objects at the same position how i saved the prefab instead of the childs taking over the child position of the object who instantiates it? See example for what I mean.instantiate problem project In the example when pressing space the child objects takes over the exact position from the instantiate caller..
Answer by InteractivePie · Oct 07, 2015 at 11:14 AM
For anyone who has the same problem: (found out the problem on my own)
It seems like if you have a prefab in your assets folder which has his own prefab as reference variable, Unity will change this into a self-reference instance variable. When you instantiate a self-reference it will also copy your positions inside the object (child objects etc.) So the workaround for me was to create another object that instantiates the prefab. This worked for me.