Advertisement
Guest User

JobifiedBaking

a guest
Dec 8th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using Unity.Collections;
  3. using Unity.Jobs;
  4. using UnityEngine;
  5. using System.Linq;
  6. using Unity.Burst;
  7.  
  8. [BurstCompile]
  9. public struct BakeJob : IJobParallelFor
  10. {
  11. private NativeArray<int> meshIds;
  12.  
  13. public BakeJob(NativeArray<int> meshIds)
  14. {
  15. this.meshIds = meshIds;
  16. }
  17.  
  18. public void Execute(int index)
  19. {
  20. Physics.BakeMesh(meshIds[index], false);
  21. }
  22. }
  23.  
  24. public static class JobifiedBaking
  25. {
  26. const int meshesPerJob = 10;
  27. public static void BakeMeshes(Dictionary<MeshChunk,Mesh> meshes)
  28. {
  29. NativeArray<int> meshIds = new NativeArray<int>(meshes.Count, Allocator.TempJob);
  30.  
  31. for (int i = 0; i < meshes.Keys.Count; ++i) {
  32. meshIds[i] = meshes[meshes.Keys.ElementAt(i)].GetInstanceID();
  33. }
  34.  
  35. // This spreads the expensive operation over all cores.
  36. var job = new BakeJob(meshIds);
  37. job.Schedule(meshIds.Length, meshesPerJob).Complete();
  38.  
  39. meshIds.Dispose();
  40.  
  41. // Now instantiate colliders on the main thread.
  42. for (int i = 0; i < meshes.Keys.Count; i++) {
  43. meshes.Keys.ElementAt(i).meshCollider.sharedMesh = meshes[meshes.Keys.ElementAt(i)];
  44. }
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement