Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Where to store result of a job?

Discussion in 'Entity Component System' started by Trond, Apr 7, 2018.

  1. Trond

    Trond

    Joined:
    Apr 14, 2013
    Posts:
    4
    I am trying to make a job that would generate a heightmap, which means i need to store the result of the job somewhere. My first though was to store it in a IComponentData, but i guess that is wrong, since having a NativeArray inside an IComponentData isn't allowed...

    Can someone explain to me how this is supposed to be done? Also, are there any multi dimensional native arrays?
     
  2. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    546
    Just pass the job an nativearray.

    (This code is just for illustration!)
    Code (CSharp):
    1.     struct Job : IJobParallelFor {
    2.         [ReadOnly] public NativeArray<int> data;
    3.         [NativeDisableParallelForRestriction] public NativeArray<int> results;
    4.  
    5.         public void Execute(int i) {
    6.             results[i] = data[i] * 10;
    7.         }
    8.     }
    9.  
    10.     void Foo() {
    11.  
    12.         NativeArray<int> data = ...
    13.         NativeArray<int> results = new NativeArray<int>(data.Length, Allocator.TempJob);
    14.         var myJob = new Job() {
    15.             data = data,
    16.             results = results,
    17.         };
    18.  
    19.          myJob.Schedule(data.Length, 1);    
    20.     }
    Don't forget to deallocate your arrays!

    Multi NativeArray: Maybe try the following...
    Code (CSharp):
    1.  
    2.   NativeArray<NativeArray<int>> multiArray = new NativeArray<NativeArray<int>>(10, Allocator.Temp);
    3.         for (int i = 0; i < multiArray.Length; i++) {
    4.             multiArray[i] = new NativeArray<int>(10, Allocator.Temp);
    5.         }
    6.  
     
  3. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    559
    the content of NativeArray must be blittable (i.e. can be memcpy'ed), but NatoveArray itself is not blittable itself. you can't have a jagged NativeArray.
    you can simulate a multidimensional NativeArray, e.g.:
    Code (csharp):
    1.  
    2. var mna = new NativeArray<int>(width*height, Allocator.Whatever);
    3. for (int i = 0; i < width; i++)
    4.   for (int j = 0; j < height; j++)
    5.     mna[i + j*width] = i*j;
    6. // ...in a job:
    7. void Execute(int index) {
    8.     int i = index % width, j = index/width;
    9.     // do your stuff...
    10. }
    11.  
     
    Desoxi and Spy-Shifty like this.