Browse Source

添加BOX适应脚本

jiajun.hu.x 2 years ago
parent
commit
67d83bbb83
2 changed files with 42 additions and 0 deletions
  1. 31 0
      Assets/JISuanBox.cs
  2. 11 0
      Assets/JISuanBox.cs.meta

+ 31 - 0
Assets/JISuanBox.cs

@@ -0,0 +1,31 @@
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+
+public class JISuanBox
+{
+    public static void setBox(GameObject gameObject)
+    {
+        Transform[] children = gameObject.GetComponentsInChildren<Transform>();
+        Bounds totalBounds = new Bounds();
+        totalBounds.center = gameObject.transform.position;
+        foreach (Transform child in children)
+        {
+            MeshRenderer meshFilter = child.GetComponent<MeshRenderer>();
+            if (meshFilter != null)
+            {
+                totalBounds.Encapsulate(meshFilter.bounds);
+            }
+        }
+
+        Vector3 totalSize = totalBounds.size;
+
+        BoxCollider box = gameObject.GetComponent<BoxCollider>();
+        if (box == null)
+        {
+            box = gameObject.AddComponent<BoxCollider>();
+        }
+        box.size = totalSize / gameObject.transform.localScale.x;
+        box.center = gameObject.transform.InverseTransformPoint(totalBounds.center);
+    }
+}

+ 11 - 0
Assets/JISuanBox.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 03cad4fc4fd1a874ca9714d8962766e7
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: