Unity 框架

AddColiider.cs 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using UnityEditor.Toolbars;
  6. namespace TFramework
  7. {
  8. [EditorToolbarElement(id, typeof(SceneView))]
  9. public class AddCollider:EditorToolbarButton
  10. {
  11. public const string id = "TCC/AddCollider";
  12. public AddCollider()
  13. {
  14. text = "";
  15. icon = EditorGUIUtility.IconContent("d_PhysicsRaycaster Icon").image as Texture2D;
  16. tooltip = "添加碰撞体";
  17. clicked += AddBoxCollider;
  18. }
  19. public static void AddBoxCollider()
  20. {
  21. Transform parent = Selection.activeGameObject.transform;
  22. //记录坐标
  23. Vector3 postion = parent.position;
  24. Quaternion rotation = parent.rotation;
  25. Vector3 scale = parent.localScale;
  26. //坐标归零
  27. parent.position = Vector3.zero;
  28. parent.rotation = Quaternion.Euler(Vector3.zero);
  29. parent.localScale = Vector3.one;
  30. //删除子物体碰撞体
  31. Collider[] colliders = parent.GetComponentsInChildren<Collider>();
  32. foreach (Collider child in colliders)
  33. GameObject.DestroyImmediate(child);
  34. //取中心点平均值
  35. Vector3 center = Vector3.zero;
  36. Renderer[] renders = parent.GetComponentsInChildren<Renderer>();
  37. foreach (Renderer child in renders)
  38. center += child.bounds.center;
  39. center /= parent.GetComponentsInChildren<Renderer>().Length;
  40. //确定包围盒
  41. Bounds bounds = new Bounds(center, Vector3.zero);
  42. foreach (Renderer child in renders)
  43. {
  44. bounds.Encapsulate(child.bounds);
  45. }
  46. BoxCollider boxCollider = parent.gameObject.AddComponent<BoxCollider>();
  47. boxCollider.center = bounds.center;
  48. boxCollider.size = bounds.size;
  49. //计算完成物体归位
  50. parent.position = postion;
  51. parent.rotation = rotation;
  52. parent.localScale = scale;
  53. EditorUtility.SetDirty(parent);
  54. AssetDatabase.SaveAssets();
  55. }
  56. }
  57. }