Search Unity

Bug ScheduleBatchedJobs not working??

Discussion in 'Scripting' started by NickUnity66, Aug 6, 2021.

  1. NickUnity66

    NickUnity66

    Joined:
    Jul 19, 2021
    Posts:
    1
    The below code shows a script trying to use ScheduleBatchJobs to run a job (AllowMultiFrames=true). The job never runs and IsComplete is always false.

    Changing AllowMultiFrames = false in the editor causes the script to use Complete() which immediately triggers the job to run fine. Even if it is several seconds after being scheduled. But Complete blocks the main thread.

    The documentation suggest that the job should be triggered by ScheduleBatchJobs but this isn't happening in this case.

    (Script just needs to be attached to empty game object to run.)


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.Collections;
    4. using Unity.Jobs;
    5. using UnityEngine;
    6.  
    7. public class JobRepo : MonoBehaviour
    8. {
    9.     public float test;
    10.  
    11.     public bool AllowMultiFrames = true;
    12.  
    13.     JobHandle HJob;
    14.     NativeArray<float> result;
    15.  
    16.     int delay = 50;//visibility in profiler
    17.     bool HasSentJob;
    18.     bool HasProcessedAnswer = false;
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if (!HasSentJob && delay-- < 0)
    24.         {
    25.             result = new NativeArray<float>(1, Allocator.Persistent, NativeArrayOptions.ClearMemory);
    26.             var job = new TestJob
    27.             {
    28.                 test = result
    29.             };
    30.             HJob = job.Schedule();
    31.             HasSentJob = true;
    32.         }
    33.     }
    34.  
    35.     private void LateUpdate()
    36.     {
    37.         if (HasSentJob && !HasProcessedAnswer)
    38.         {
    39.             if (AllowMultiFrames && !HJob.IsCompleted)
    40.             {
    41.                 JobHandle.ScheduleBatchedJobs();
    42.             }
    43.             else
    44.             {
    45.                 HJob.Complete();
    46.                 test = result[0];
    47.                 result.Dispose();
    48.  
    49.                 HasProcessedAnswer = true;
    50.             }
    51.         }
    52.     }
    53. }
    54.  
    55.  
    56.  
    57. public struct TestJob : IJob
    58. {
    59.     public NativeArray<float> test;
    60.  
    61.     public void Execute()  
    62.     {
    63.  
    64.         for (int i = 0; i < 9999999; i++)
    65.         {
    66.             test[0] = Mathf.Cos(Mathf.Sin(45));
    67.         }
    68.     }
    69. }
     
    Last edited: Aug 9, 2021