Hello,
I’m instantiating a number of prefabs and assigning their position based on the previous prefabs position plus a variable amount. The prefabs are all children of the game object that instantiated them. I would like the entire game object including prefabs to be the center of the game object, however Unity is showing the position to be the first prefab’s position. How can I reassign the pivot to be at the center of the entire game object hierarchy within code?
1 Like
prefab.transform.parent = transform;
prefab.transform.localPosition = Vector3.zero;
1 Like
Thank you for your reply. However it’s not a single prefab but a number of prefabs that are being instantiated starting from Vector3.zero, positioning down the x axis. I want to reassign the pivot to the center as opposed to the origin where I began.
so, you want to average all of the positions, or do you want to get the center of the bounds of the graphics?
You can use gameObject.GetComponentsInChildren(MeshFilter); then use Bounds.Encapsulate to get the overall mesh bounds of the game object and all of it’s children. From there it is just a bounds. Bounds.center will do what you wish.
Can you explain this a little further? It sounds like it may be the right track. I’m thinking I’m going to have to move the entire hierarchy to the left and upwards to offset the position to the center of the origin. I would need to move 1/2 the bounds width to the left and 1/2 the bounds height upwards.