Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Passing array into a Job from external source

Discussion in 'Scripting' started by OJDee, Jan 28, 2021.

  1. OJDee

    OJDee

    Joined:
    Feb 11, 2014
    Posts:
    64
    Hi

    I have a class running a variety of jobs, and I want to pass an array of floats into this class from an external class so that one of the Jobs can access it.

    Currently I have

    In Job handling class

    public NativeList<float>Values

    And initialised

    Values = new NativeList<float>(0, Allocator.Persistent);



    On struct : IJobParallelFor

    [ReadOnly] public NativeList<float>JobValues


    In struct Constructor

    JobValues = Values



    External class

    * parentClass.Values = anArray.ToNativeList<float>(Allocator.Persistent);

    And then run the jobs on parent class



    Receiving error
    A Native Collection has not been disposed, resulting in a memory leak. Allocated from: { refers to the * line above }

    I am confused as I thought persistent allocation of native objects did not require disposal.
    If they do, I am not sure where to Dispose() in this stack?

    Is this even the right way to pass variables into a Job from a third party?


    Thanks for any tips.
     
  2. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    You still need to dispose them eventually when they are no longer needed. For example:

    Code (CSharp):
    1. void OnEnable()
    2. {
    3.     Values = new NativeList<float>(0, Allocator.Persistent);
    4. }
    Code (CSharp):
    1. void OnDisable()
    2. {
    3.     Values.Dispose();
    4. }
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,528
    Right however keep in mind that a line like this
    will replace the old native array without disposing it. If the native list is created outside, you shouldn't manually create another NativeList
     
  4. OJDee

    OJDee

    Joined:
    Feb 11, 2014
    Posts:
    64
    I think this was the issue. I was creating a new NativeArray and assigning from external source. I should just modify the single original nativearray and let it be disposed once.