JISuanBox.cs 987 B

12345678910111213141516171819202122232425262728293031
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class JISuanBox
  5. {
  6. public static void setBox(GameObject gameObject)
  7. {
  8. Transform[] children = gameObject.GetComponentsInChildren<Transform>();
  9. Bounds totalBounds = new Bounds();
  10. totalBounds.center = gameObject.transform.position;
  11. foreach (Transform child in children)
  12. {
  13. MeshRenderer meshFilter = child.GetComponent<MeshRenderer>();
  14. if (meshFilter != null)
  15. {
  16. totalBounds.Encapsulate(meshFilter.bounds);
  17. }
  18. }
  19. Vector3 totalSize = totalBounds.size;
  20. BoxCollider box = gameObject.GetComponent<BoxCollider>();
  21. if (box == null)
  22. {
  23. box = gameObject.AddComponent<BoxCollider>();
  24. }
  25. box.size = totalSize / gameObject.transform.localScale.x;
  26. box.center = gameObject.transform.InverseTransformPoint(totalBounds.center);
  27. }
  28. }