Hello everyone!
I want to achieve following:
- Generate mesh on MonoBehaviour side
- Transfer mesh to ECS
- Generate mesh collider based on obtained mesh data
- I want to attach generated collider to the entity which is child of another entity. I don’t want the generated collider to be visible
What I did so far:
- Created managed component containing Mesh property:
public class MeshDataComponent : IComponentData, IDisposable
{
public Mesh Mesh;
public void Dispose()
{
UnityEngine.Object.Destroy(Mesh);
}
}
- I filled Mesh property with valid mesh data and attached MeshDataComponent to the entity on which I want the collider to be generated
- Then I created system for the collider generation:
[BurstCompile]
[UpdateInGroup(typeof(InitializationSystemGroup))]
public partial struct MeshColliderInitializationSystem : ISystem, ISystemStartStop
{
private BlobAssetReference<Unity.Physics.Collider> _createdColliderBlob;
private EntityQuery _entityQuery;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<MeshDataComponent >();
}
private void ISystemStartStop.OnStartRunning(ref SystemState state)
{
_entityQuery = SystemAPI.QueryBuilder()
.WithAll<MeshDataComponent>()
.Build();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
// Make sure this system runs only once
state.Enabled = false;
EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);
// Get relevant entity and component
Entity targetColliderEntity = _entityQuery.GetSingletonEntity();
MeshDataComponent meshData = _entityQuery.GetSingleton<MeshDataComponent>();
// Creation of collider blob
_createdColliderBlob = Unity.Physics.MeshCollider.Create(meshData.Mesh,
CollisionFilter.Default, Unity.Physics.Material.Default);
// Create physics collider based on blob data and assign it to the entity
PhysicsCollider collider = new PhysicsCollider() { Value = _createdColliderBlob };
ecb.AddComponent<PhysicsCollider>(targetColliderEntity, collider);
ecb.Playback(state.EntityManager);
ecb.Dispose();
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
_createdColliderBlob.Dispose();
}
public void OnStopRunning(ref SystemState state) { }
}
Result:
- Expected collider is not in the scene and I experience no additional collisions, although if I go and inspect the target entity in the editor I can see that PhysicsCollider component has been sucessfully added to the entity, it just seems like it’s collisions are completely non-working.
I double checked Mesh property in MeshDataComponent and this seems to be assigned correctly, so I think my problem is related to the System code - probably I am missing some important part? Can please someone suggest me where the problem could be?
Thanks in advance for your answers!