- Home /
Reset GameObject Axis Origin at Model Center
I'm trying to find the centre point of a model, and reposition the axis (handle) to this point - actually, I'm spawning an Empty GameObject to this point, and then placing the model inside of this, and using the Empty GameObject as the parent (thus having the origin centred).
However my formula doesn't seem to find the centre correctly on most test models I have. I'm wondering if Unity has a built-in calc for this? I basically want to use the same results that the 'Toggle Tool Handle Position' does in the Editor;
Here is a model with a non-centred handle (looking top down);
Using the 'Toggle Tool Handle Position' to 'Center' places the handle perfectly in the centre of the model (as you'd expect). So my question is what is the calculation for this, so I can duplicate this via code?
NOTE; The purpose of this project is to allow the user import any FBX, so the centre point may have potential of being completely off, and out of designer control.
Currently, I cycle through all the children of the model, and use the mesh bounds to calculate a centre points. But it doesn't always give the correct results on certain models.
private static Vector3 FindCentroid(Transform _parent, List<Transform> targets) {
Vector3 centroid;
Vector3 minPoint = targets[0].position;
Vector3 maxPoint = targets[0].position;
for (int i = 1; i < targets.Count; i++) {
if (targets[i].GetComponent<MeshRenderer>() != null) {
Vector3 pos = targets[i].GetComponent<MeshRenderer>().bounds.center;
if (pos.x < minPoint.x)
minPoint.x = pos.x;
if (pos.x > maxPoint.x)
maxPoint.x = pos.x;
if (pos.y < minPoint.y)
minPoint.y = pos.y;
if (pos.y > maxPoint.y)
maxPoint.y = pos.y;
if (pos.z < minPoint.z)
minPoint.z = pos.z;
if (pos.z > maxPoint.z)
maxPoint.z = pos.z;
}
}
centroid = minPoint + 0.5f * (maxPoint - minPoint);
Vector3 _center = new Vector3(centroid.x, _parent.position.y, centroid.z);
return _center;
}
Answer by wewewu · Jun 09, 2020 at 09:00 AM
Probuilderize the Gameobject so you can change the pivot with probuilder.