No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CollectionsExamples.cs 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections.Generic;
  2. using Unity.Collections;
  3. using Unity.Jobs;
  4. namespace Doc.CodeSamples.Collections.Tests
  5. {
  6. struct ExamplesCollections
  7. {
  8. public void foo()
  9. {
  10. #region parallel_writer
  11. NativeList<int> nums = new NativeList<int>(1000, Allocator.TempJob);
  12. // The parallel writer shares the original list's AtomicSafetyHandle.
  13. var job = new MyParallelJob {NumsWriter = nums.AsParallelWriter()};
  14. #endregion
  15. }
  16. #region parallel_writer_job
  17. public struct MyParallelJob : IJobParallelFor
  18. {
  19. public NativeList<int>.ParallelWriter NumsWriter;
  20. public void Execute(int i)
  21. {
  22. // A NativeList<T>.ParallelWriter can append values
  23. // but not grow the capacity of the list.
  24. NumsWriter.AddNoResize(i);
  25. }
  26. }
  27. #endregion
  28. public void foo2()
  29. {
  30. #region enumerator
  31. NativeList<int> nums = new NativeList<int>(10, Allocator.Temp);
  32. // Calculate the sum of all elements in the list.
  33. int sum = 0;
  34. var enumerator = nums.GetEnumerator();
  35. // The first MoveNext call advances the enumerator to the first element.
  36. // MoveNext returns false when the enumerator has advanced past the last element.
  37. while (enumerator.MoveNext())
  38. {
  39. sum += enumerator.Current;
  40. }
  41. // The enumerator is no longer valid to use after the array is disposed.
  42. nums.Dispose();
  43. #endregion
  44. }
  45. #region read_only
  46. public struct MyJob : IJob
  47. {
  48. // This array can only be read in the job.
  49. [ReadOnly] public NativeArray<int> nums;
  50. public void Execute()
  51. {
  52. // If safety checks are enabled, an exception is thrown here
  53. // because the array is read only.
  54. nums[0] = 100;
  55. }
  56. }
  57. #endregion
  58. }
  59. }