Updating Box Collider with Skinned Mesh Renderer when Animating in Unity

Updating Box Collider with Skinned Mesh Renderer when Animating in Unity


When animating a 3D character with a skinned mesh in Unity, you often want to update its box collider bounds to match the current pose. Here is how to accomplish this:

First, attach both a Skinned Mesh Renderer and Box Collider to your character. Make sure the box collider is set to auto-generate so it fits the mesh.

In a script, cache the Skinned Mesh Renderer and Box Collider components:

```

SkinnedMeshRenderer skin;

BoxCollider boxCollider;

void Start() {

  skin = GetComponent<SkinnedMeshRenderer>();

  boxCollider = GetComponent<BoxCollider>();

}

```

Next, in the Update loop, call the UpdateBounds method of the box collider:

```

void Update() {

  boxCollider.UpdateBounds();

}

```

This will automatically refit the box collider to the skinned mesh bounds.

For optimization, you can disable this update when not animating:

```

if(skin.isVisible && animator.IsPlaying()) {

  boxCollider.UpdateBounds(); 

}

```

This will keep the box collider fitting the skinned mesh as it animates. You may also want to tweak the box collider settings like Center and Size for finer tuning.

Updating bounds is important for proper physics interactions between animated characters and other colliders. This approach keeps the collider synchronized with the animated skinned mesh renderer in Unity.