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.

CollectionsAllocationExamples.cs 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using Unity.Collections;
  2. using Unity.Jobs;
  3. namespace Doc.CodeSamples.Collections.Tests
  4. {
  5. class AliasingExample
  6. {
  7. public void foo()
  8. {
  9. #region allocation_aliasing
  10. NativeList<int> nums = new NativeList<int>(10, Allocator.TempJob);
  11. nums.Length = 5;
  12. // Create an array of 5 ints that aliases the content of the list.
  13. NativeArray<int> aliasedNums = nums.AsArray();
  14. // Modify the first element of both the array and the list.
  15. aliasedNums[0] = 99;
  16. // Only the original need be disposed.
  17. nums.Dispose();
  18. // Throws an ObjectDisposedException because disposing
  19. // the original deallocates the aliased memory.
  20. aliasedNums[0] = 99;
  21. #endregion
  22. }
  23. public void foo2()
  24. {
  25. #region allocation_reinterpretation
  26. NativeArray<int> ints = new NativeArray<int>(10, Allocator.Temp);
  27. // Length of the reinterpreted array is 20
  28. // (because it has two shorts per one int of the original).
  29. NativeArray<short> shorts = ints.Reinterpret<int, short>();
  30. // Modifies the first 4 bytes of the array.
  31. shorts[0] = 1;
  32. shorts[1] = 1;
  33. int val = ints[0]; // val is 65537 (2^16 + 2^0)
  34. // Like with other aliased collections, only the original
  35. // needs to be disposed.
  36. ints.Dispose();
  37. // Throws an ObjectDisposedException because disposing
  38. // the original deallocates the aliased memory.
  39. shorts[0] = 1;
  40. #endregion
  41. }
  42. public void foo3()
  43. {
  44. #region allocation_dispose_job
  45. NativeArray<int> nums = new NativeArray<int>(10, Allocator.TempJob);
  46. // Create and schedule a job that uses the array.
  47. ExampleJob job = new ExampleJob { Nums = nums };
  48. JobHandle handle = job.Schedule();
  49. // Create and schedule a job that will dispose the array after the ExampleJob has run.
  50. // Returns the handle of the new job.
  51. handle = nums.Dispose(handle);
  52. #endregion
  53. }
  54. }
  55. struct ExampleJob : IJob
  56. {
  57. public NativeArray<int> Nums;
  58. public void Execute()
  59. {
  60. throw new System.NotImplementedException();
  61. }
  62. }
  63. }