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