Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Best Practices - Creating a bunch of unique meshcolliders?

Discussion in 'Physics for ECS' started by JeremieTessierOuterminds, Sep 8, 2020.

  1. JeremieTessierOuterminds

    JeremieTessierOuterminds

    Joined:
    Oct 22, 2019
    Posts:
    3
    Hello everyone!

    I've been using DOTS for a little while now and just got into the world of Unity.Physics to replace my old rigidbodies of yore. I have a few objects in my game that I have to instantiate, all with their different and unique meshcolliders (I can't really use boxes because these objects might have holes in them and I need precise raycasting).

    I've been trying to add them using code looking like this, but it's horribly slow, am I doing something wrong? And if so, what?

    Code (CSharp):
    1.  
    2. var meshTris = new NativeArray<int3>(mesh.triangles.Length / 3, Allocator.Temp);
    3. var meshVertices = new NativeArray<float3>(mesh.vertices.Length, Allocator.Temp);
    4.  
    5. int index = 0;
    6. foreach (Vector3 v in mesh.vertices)
    7.     meshVertices[index++] = v;
    8.  
    9. index = 0;
    10. for (int j = 0; j < mesh.triangles.Length; j += 3)
    11.     meshTris[index++] = new int3(mesh.triangles[j], mesh.triangles[j + 1], mesh.triangles[j + 2]);
    12.  
    13. BlobAssetReference<Collider> meshColliderReference = Unity.Physics.MeshCollider.Create(meshVertices, meshTris, Unity.Physics.CollisionFilter.Default, Unity.Physics.Material.Default);
    14.  
    15. Entity source = entityManager.CreateEntity();
    16. PhysicsMass pm = PhysicsMass.CreateDynamic(meshColliderReference.Value.MassProperties, 1f);
    17. entityManager.AddComponentData(source, new PhysicsCollider() { Value = meshColliderReference });
    18. entityManager.AddComponentData(source, pm);
    Many thanks!
     
  2. petarmHavok

    petarmHavok

    Joined:
    Nov 20, 2018
    Posts:
    461
    Unfortunately mesh creation is a slow process, especially for large meshes with a lot of triangles. You could put mesh creation part in a Burst compiled job, that should speed it up significantly. Check CreateTempMeshJob in PhysicsShapeAuthoringEditor.cs for usage.
     
  3. Sima_Havok

    Sima_Havok

    Joined:
    Dec 16, 2019
    Posts:
    52
    Would approximation of your mesh collider with compound of convex colliders be a viable option?