Search Unity

Question NativeArray.Slice throughs ArgumentException: Slice may not be used on a restricted range array

Discussion in 'Entity Component System' started by Stranger-Games, Feb 19, 2021.

  1. Stranger-Games

    Stranger-Games

    Joined:
    May 10, 2014
    Posts:
    393
    Hi,

    Passing a persistent allocated nativearray to a job's constructor then calling Slice on it always throws. ArgumentException: Slice may not be used on a restricted range array
    I tried Slice(0,1) to make sure I am not overflowing the index and still got the same exception.

    Code (CSharp):
    1.  
    2.     public struct Job : IJobParallelFor
    3.     {
    4.         public NativeArray<Vector3> summonedPos;
    5.  
    6.         public void Execute(int index)
    7.         {
    8.             var ns = summonedPos.Slice(0, 1);
    9.             //ArgumentException: Slice may not be used on a restricted range array
    10.             //I checked and positive that summonedPos length is more than 1
    11.         }
    12.     }
    13.  
    14.    public class JobManager : MonoBehaviour
    15.     {
    16.         private NativeArray<SpawnPoint.ParallelData> _spawnersArray;
    17.         private Job _job;
    18.        
    19.        public void Initialize()
    20.         {
    21.             _summonedPos = new NativeArray<Vector3>(_spawnPoints.Length * 50, Allocator.Persistent);
    22.             _job = new Job
    23.             {
    24.                 summonedPos = _summonedPos
    25.             };
    26.         }
    27.  
    Thanks for advance.
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Because you're in a parallel job so what index you can use on the NativeArray is restricted for safety.

    Either you need to mark the NativeArray [ReadOnly] (the best approach) or if you are certain it's safe to write to an arbitrary index you need to use [NativeDisableParallelForRestriction]
     
    tonytopper and Stranger-Games like this.
  3. Stranger-Games

    Stranger-Games

    Joined:
    May 10, 2014
    Posts:
    393
    Thank you very much.
    I will use NativeDisableParallelForRestriction, since it's a multidimensional array and each thread has a distinct slice (inner array) so the threads won't overwrite each other.