Object pivot changer in unity

PivotChanger

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PivotChanger : MonoBehaviour
{
    public Transform TargetModel; //That model we want to change the pivot point of it
    public List<Transform> model; //These are children of target model 
    public GameObject centerpoint; // Final result as a new object
    public List<Vector3> Points; // These are vector3 of position of model objects


    private void Start()
    {
        //ChangeObjectsPivot();
    }

    [ContextMenu("ChangeObjectsPivot")]
    public void ChangeObjectsPivot()
    {
        foreach (Transform child in TargetModel)
        {
            model.Add(child);
        }

        centerpoint = new GameObject("Centerpoint");
        centerpoint.transform.parent = model[0].parent;
        for (int i = 0; i < model.Count; i++)
        {
            model[i].gameObject.AddComponent<BoxCollider>();
            Points.Add(model[i].gameObject.GetComponent<BoxCollider>().center);
            Destroy(model[i].gameObject.GetComponent<BoxCollider>());
        }
        centerpoint.transform.localPosition = FindCenterOfTransforms(Points);
        centerpoint.transform.parent = null;
        TargetModel.parent = centerpoint.transform;
        centerpoint.transform.position = Vector3.zero;
    }

    Vector3 FindCenterOfTransforms(List<Vector3> points)
    {
        var bound = new Bounds(points[0], Vector3.zero);
        for (int i = 1; i < points.Count; i++)
        {
            bound.Encapsulate(points[i]);
        }
        return bound.center;
    }

    [ContextMenu("ChangeSingleObjectPivot")]
    public void ChangeSingleObjectPivot()
    {
        centerpoint = new GameObject("Centerpoint");
        centerpoint.transform.parent = TargetModel.parent;

        TargetModel.gameObject.AddComponent<BoxCollider>();
        Points.Add(TargetModel.gameObject.GetComponent<BoxCollider>().center);
        Destroy(TargetModel.gameObject.GetComponent<BoxCollider>());
        
        centerpoint.transform.localPosition = Points[0];
        centerpoint.transform.parent = null;
        TargetModel.parent = centerpoint.transform;
        centerpoint.transform.position = Vector3.zero;
    }
}


Content ©2023 Abolfazl Tanha All Rights Reserved​​​​​​​