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 Variables to a Job?

Discussion in 'Editor & General Support' started by brolol404, Sep 11, 2020.

  1. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    I am trying to learn the Job System, but I can't seem to pass variables to a Job? I may not be using Jobs correctly, but I am trying to multi-thread my code. The code works without using Jobs.
     
    Last edited: Sep 13, 2020
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,120
    The job struct itself is essentially the variable and the functionality in one. Definitely don't try to access data outside of the job itself. In most cases, that isn't safe memory. So, things like Transforms, Rigidbodies, that's off limits in a job.

    Anyway, what you can do is make public fields on your job struct, and assign values to them before running the job. Here's how one of my job structs starts:

    Code (CSharp):
    1.         [BurstCompile(CompileSynchronously = true)]
    2.         private struct GenerateVisibilityRaycastCommandsJob : IJobParallelFor
    3.         {
    4.             [ReadOnly]
    5.             public Vector3 ObjectPosition;
    6.             [ReadOnly]
    7.             public float MaxEffectRange;
    8.  
    9.             public NativeArray<ObjectVisibilityObjectData> ObjectVisibilityObjectInputData;
    10.  
    11.             public NativeArray<RaycastCommand> RaycastCommands;
    Those fields can be populated before running the job, and read after running the job. Generally, you shouldn't be reading/writing any other data from within the job. You can maybe get away with writing to some static fields, but I'd try to just keep everything in the job.
     
  3. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    Thanks. I think I may be going about this the wrong way then. Instead of trying to have jobs complete repetitive tasks within scripts, I should probably just be using jobs to complete entire scripts that are performed multiple times.

    Can jobs read variables from other scripts or do they need to be all inclusive?

     
  4. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,120
    You really need to give the job all the data it's going to act on. Think of jobs kind of like sending some data away for processing. You need to supply all the data to it, and it will process only the data you give it. Often, the slowest thing about jobs is putting the data in and getting the data out again. The actual processing of the job is incredibly fast once you start it.
     
    brolol404 likes this.