How to bake CollisionFilter?

Hi, unity teams :slight_smile:

I’m trying to use the following code to override CollisionFilter.GroupIndex at baking time. But I find that sometimes the GroupIndex is not what I expected.

It looks like that if two objects have same Collider shape / layer, they will share the same BlobAssetReference. So they can’t have different GroupIndex. Am I right? Is there any solution?

Thanks : D

        [WorldSystemFilter(WorldSystemFilterFlags.BakingSystem)]
        [UpdateInGroup(typeof(PostBakingSystemGroup))]
        private partial struct BakeSystem : ISystem
        {
            public void OnUpdate(ref SystemState state)
            {
                using var buffer = new EntityCommandBuffer(Allocator.Temp);
                foreach (var (@override, collider, e) in SystemAPI
                             .Query<PhysicsGroupIndexOverride, RefRW<PhysicsCollider>>()
                             .WithOptions(EntityQueryOptions.IncludePrefab).WithEntityAccess())
                {
                    var newCollider = collider.ValueRW.Value.Value.Clone();
                    var filter = newCollider.Value.GetCollisionFilter();
                    filter.GroupIndex = @override.GroupIndex;
                    newCollider.Value.SetCollisionFilter(filter);
                    collider.ValueRW.Value = newCollider;

                    buffer.RemoveComponent<PhysicsGroupIndexOverride>(e);
                }

                buffer.Playback(state.EntityManager);
            }

I found a similar question, but it seems only work at runtime.

Yes. If you need unique colliders per rigid body, just use the force unique option when baking, or PhysicsCollider.MakeUnique() at runtime.
See the collider documentation for more details.

thanks @daniel-holz :slight_smile:

for anyone else running into this problem, solution:
https://docs.unity3d.com/Packages/com.unity.physics@1.2/manual/physics-collider-components.html#making-colliders-unique-during-authoring

1 Like