using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Toolbars;

namespace TFramework
{
    [EditorToolbarElement(id, typeof(SceneView))]
    public class AddCollider:EditorToolbarButton
    {
        public const string id = "TCC/AddCollider";

        public AddCollider()
        {
            text = "";
            icon = EditorGUIUtility.IconContent("d_PhysicsRaycaster Icon").image as Texture2D;
            tooltip = "添加碰撞体";
            clicked += AddBoxCollider;
        }

        public static void AddBoxCollider()
        {
            Transform parent = Selection.activeGameObject.transform;
            //记录坐标
            Vector3 postion = parent.position;
            Quaternion rotation = parent.rotation;
            Vector3 scale = parent.localScale;
            //坐标归零
            parent.position = Vector3.zero;
            parent.rotation = Quaternion.Euler(Vector3.zero);
            parent.localScale = Vector3.one;
            //删除子物体碰撞体
            Collider[] colliders = parent.GetComponentsInChildren<Collider>();
            foreach (Collider child in colliders)
                GameObject.DestroyImmediate(child);

            //取中心点平均值
            Vector3 center = Vector3.zero;
            Renderer[] renders = parent.GetComponentsInChildren<Renderer>();
            foreach (Renderer child in renders)
                center += child.bounds.center;

            center /= parent.GetComponentsInChildren<Renderer>().Length;
            //确定包围盒
            Bounds bounds = new Bounds(center, Vector3.zero);
            foreach (Renderer child in renders)
            {
                bounds.Encapsulate(child.bounds);
            }
            BoxCollider boxCollider = parent.gameObject.AddComponent<BoxCollider>();
            boxCollider.center = bounds.center;
            boxCollider.size = bounds.size;

            //计算完成物体归位
            parent.position = postion;
            parent.rotation = rotation;
            parent.localScale = scale;
            EditorUtility.SetDirty(parent);
            AssetDatabase.SaveAssets();
        }
    }
}
