Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Unity.Collections;
- using UnityEngine;
- using Unity.Jobs;
- using Unity.Burst;
- public class LongJob : MonoBehaviour
- {
- public long totalSteps = 1;
- public long intermediateSteps = 1;
- private LongLongJob theJob;
- private NativeArray<long> results;
- private JobHandle longHandle;
- private int numJobs = 0;
- private long currentStep = 0;
- private int jobIndex = 0;
- [BurstCompile]
- struct LongLongJob : IJob
- {
- public long input;
- public NativeArray<long> output;
- public long steps;
- public int resultIndex;
- public void Execute()
- {
- for (long i = 0; i < steps; i++)
- {
- output[resultIndex]++;
- }
- output[resultIndex] += input;
- }
- }
- private void scheduleJob(long inputValue, long steps, int index)
- {
- theJob = new LongLongJob()
- {
- steps = steps,
- input = inputValue,
- output = results,
- resultIndex = index
- };
- longHandle = theJob.Schedule(longHandle);
- }
- void Start()
- {
- numJobs = (int)((totalSteps + intermediateSteps - 1) / intermediateSteps);
- results = new NativeArray<long>(numJobs, Allocator.Persistent, NativeArrayOptions.ClearMemory);
- }
- private bool done = false;
- void Update()
- {
- if (currentStep < totalSteps && longHandle.IsCompleted)
- {
- longHandle.Complete();
- long previousResults = jobIndex > 0 ? results[jobIndex - 1] : 0;
- Debug.Log("Previous intermediate result: " + jobIndex + " = " + previousResults);
- long nextSteps = totalSteps - currentStep > intermediateSteps
- ? intermediateSteps
- : totalSteps - currentStep;
- scheduleJob(previousResults, nextSteps, jobIndex++);
- currentStep += nextSteps;
- } else if(currentStep >= totalSteps && longHandle.IsCompleted && !done) {
- longHandle.Complete();
- Debug.Log("Result: " + results[results.Length - 1]);
- done = true;
- }
- }
- private void OnDestroy()
- {
- longHandle.Complete();
- results.Dispose();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement