给物体添加碰撞体,使碰撞器刚好包围物体
程序员文章站
2024-03-16 15:26:04
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetModel : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Vector3 postion = transform.position;
Quaternion rotation = transform.rotation;
Vector3 scale = transform.localScale;
transform.position = Vector3.zero;
transform.rotation = Quaternion.Euler(Vector3.zero);
transform.localScale = Vector3.one;
Collider[] colliders = transform.GetComponentsInChildren<Collider>();
foreach (Collider child in colliders)
{
DestroyImmediate(child);
}
Vector3 center = Vector3.zero;
Renderer[] renders = transform.GetComponentsInChildren<Renderer>();
foreach (Renderer child in renders)
{
center += child.bounds.center;
}
center /= transform.GetComponentsInChildren<Transform>().Length;
Bounds bounds = new Bounds(center, Vector3.zero);
foreach (Renderer child in renders)
{
bounds.Encapsulate(child.bounds);
}
BoxCollider boxCollider = transform.gameObject.AddComponent<BoxCollider>();
boxCollider.center = bounds.center - transform.position;
boxCollider.size = bounds.size;
transform.position = postion;
transform.rotation = rotation;
transform.localScale = scale;
}
void Update()
{
}
}
推荐阅读