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