Reputation: 33
I am trying to instantiate a prefab as a child, and I want it's location to be the exact same as it's parent. Somehow the prefab is not instantiated on the exact same position.
The parent is also a child of another object. For clarity:
"Selectable(Clone)" is the instantiated prefab. I want the position to be the same as the "Lader" position.
My Code:
Vector3 position = new Vector3(0, 0, 0);
GameObject obj = Instantiate(prefab);
obj.transform.parent = parent.transform;
obj.transform.localPosition = position;
Could someone help me with this? Thanks in advance!
Upvotes: 1
Views: 11234
Reputation: 379
You can instantiate direct the child transform using the Instantiate()
try:
Instantiate(GameObeject, transformPosition, Quaternion.identity, transformParent);
Exemple:
Instantiate(popUpMsg, Canvas.transform.position, Quaternion.identity, Canvas.transform);
Now PopUp GameObject is Canvas' child
Upvotes: 0
Reputation: 474
Did you try to set the position before setting the parent?
Vector3 position = new Vector3(0, 0, 0);
GameObject obj = Instantiate(prefab);
obj.transform.Position = parent.transform.position;
obj.transform.parent = parent.transform;
Upvotes: 1
Reputation: 568
I think that's what you're looking for. Make sure both child and parent pivots are centered.
GameObject obj = Instantiate(prefab);
obj.transform.SetParent(parent, false);
Upvotes: 2
Reputation: 101
Maybe you can try something like this:
obj.transform.position = parent.transform.position;
Upvotes: 0
Reputation: 1884
Here, you are not specifying that the new GameObject is to be a child of anything, so be sure to do this.
public GameObject parentLadder;
public GameObject prefab
Next, don't call a variable position, as it's already a unity global.
Vector3 pos = (0,0,0)
Then actually instantiate our object and set it to parent transform.
GameObject obj = Instantiate(prefab, transform.position, transform.rotation) as GameObject;
obj.transform.position = parentLadder.transform.position;
obj.transform.localPosition = pos;
Upvotes: 0