Issue with fbx box collider

Hi,

In my project I have to instantiate a fbx model and add a box collider on it, based on children’s bounds (because the parent is an empty gameobject). I used the following code (picked up from other answers):

public class CreateBoxCollider : MonoBehaviour {

	void Start () {
		Quaternion currentRotation = this.transform.rotation;
		this.transform.rotation = Quaternion.Euler (0f, 0f, 0f);

		Bounds bounds = new Bounds (this.transform.position,  Vector3.zero);

		foreach (Renderer renderer in GetComponentsInChildren<Renderer>()) {
			bounds.Encapsulate (renderer.bounds);
		}

		Vector3 localCenter = bounds.center - this.transform.position;
		bounds.center = localCenter;

		this.transform.rotation = currentRotation;

		BoxCollider bc = this.GetComponent<BoxCollider> ();
		bc.center = localCenter;
		bc.size = bounds.size;
	}
}

The problem is that the box collider created on the parent with this script is much bigger than the model. Here’s the result : alt text

The y size seems right, but is there a reason why x and z sizes aren’t ?

@Phelyz

Is it really necessary to create box colliders dynamically?

Just make a prefab out of your FBX model and add appropriate box collider on every single bone in your model which you need directly in the editor.

After, just instantiate your ready to go prefab instead.

Note: use void OnTriggerEnter(Collider col) event to detect collision instead of OnCollisionEnter to avoid some strange mismatches with collisions. It gives me a lot of troubles then I was using OnCollisionEnter event instead…