Tối ưu với Job System & Burst Compiler
C# Code
// Yêu cầu: Cài đặt các gói 'Jobs', 'Burst', 'Collections' từ Package Manager.
using Unity.Collections;
using Unity.Jobs;
using Unity.Burst;
using UnityEngine;
public class JobSystemExample : MonoBehaviour
{
void Start()
{
NativeArray<float> inputArray = new NativeArray<float>(1000, Allocator.TempJob);
NativeArray<float> outputArray = new NativeArray<float>(1000, Allocator.TempJob);
// Tạo một job
MyJob jobData = new MyJob {
input = inputArray,
output = outputArray
};
// Lên lịch thực thi job
JobHandle handle = jobData.Schedule(inputArray.Length, 64);
// Chờ job hoàn thành
handle.Complete();
// Sử dụng kết quả
Debug.Log("Kết quả job: " + outputArray[0]);
// Giải phóng bộ nhớ của NativeArray
inputArray.Dispose();
outputArray.Dispose();
}
}
// [BurstCompile] sẽ tối ưu hóa job này thành mã máy cực nhanh
[BurstCompile]
public struct MyJob : IJobParallelFor
{
[ReadOnly] public NativeArray<float> input;
public NativeArray<float> output;
public void Execute(int index)
{
// Logic tính toán phức tạp ở đây
output[index] = input[index] * 2.0f;
}
}Giới thiệu về DOTS (Data-Oriented Technology Stack) bằng cách sử dụng Job System để thực hiện các tác vụ nặng song song trên nhiều luồng CPU và Burst Compiler để tối ưu hóa code C# thành mã máy cực nhanh.