How is the 'center' in Scene view calculated?

Hey guys, I’ve been fighting an issue lately. I have 2 empty parent objects, each has a different set of meshes, but they both form the same shape (think a mesh cut up in 2 ways. Now, I need to align their centers, but I failed to do so. I tried these methods:

  • sum the positions of the children and divide by their count, then unparent children, move parent to the position and parent them back

  • same as above but with collider.bounds.center

  • same as above but with renderer.bounds.center

  • same as about but with mesh.counds.center

  • take the min and max positions of any of the children, divide by 2 and then continue as above

     function CenterOnChildren (tr : Transform) {
     	var pos = Vector3.zero;
     	var rens : Renderer[] = tr.gameObject.GetComponentsInChildren.<Renderer>();	
     	for(var r in rens) {
     		pos += r.transform.position;
     		//pos += r.bounds.center;
     		r.transform.parent = null;
     	}
     	tr.position = pos / rens.Length;
     	for(r in rens) r.transform.parent = tr;
     	tr.localPosition = Vector3.zero;
     }
    

They all produce similar results, but one of them always seems to be slightly mis-aligned, which would be fine, because they could be slightly different, except the Scene view editor somehow manages to calculate their centers properly.

When I align them by hand, switch the pivot mode to
alt text then their centers match.

My question is: Can I access this center position? If not, how does the Scene view editor calculate the ‘center’ point?

Thanks,

David

The solution is to use a combination of the min/max approach and bounds.

function CenterOnChildren (tr : Transform) {
	
	var minX : float = Mathf.Infinity;
    var minY : float = Mathf.Infinity;
    var minZ : float = Mathf.Infinity;
 
    var maxX : float = -Mathf.Infinity;
    var maxY : float = -Mathf.Infinity;
    var maxZ : float = -Mathf.Infinity;
    
    var rens : Renderer[] = tr.gameObject.GetComponentsInChildren.<Renderer>();	
    
    for(var t in rens) {
    	
		if (t.bounds.min.x < minX) minX = t.bounds.min.x;
		if (t.bounds.min.y < minY) minY = t.bounds.min.y;
		if (t.bounds.min.z < minZ) minZ = t.bounds.min.z;
		if (t.bounds.max.x > maxX) maxX = t.bounds.max.x;
		if (t.bounds.max.y > maxY) maxY = t.bounds.max.y;
		if (t.bounds.max.z > maxZ) maxZ = t.bounds.max.z;

     	t.transform.parent = null;
    }

    tr.position = Vector3((minX+maxX)/2.0,(minY+maxY)/2.0,(minZ+maxZ)/2.0);

    for(r in rens) r.transform.parent = tr;
	
	tr.localPosition = Vector3.zero;
}

–David