Job system이란?
- 유니티 엔진과 연동되는 멀티스레드 코드를 작성하고, 사용할 수 있다.
- 동시에 이루어져야 할 작업과 시간이 오래 걸리는 작업에서 주로 사용된다.
- Job은 워커스레드에서 실행된다.
Job이란?
사용방법
- 생성해준 구조체에 IJob을 상속시켜준다.
- IJob은 구조체에 사용되며, Execute라는 메서드를 꼭 만들어 주어야한다.
- Execute 메서드에는 파라미터 값이 없다.
- Execute메서드 안에 실행할 작업 내용을 써넣는다.
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
public class Test : MonoBehaviour
{
public GameObject go;
private NativeArray<ulong> result = new NativeArray<ulong>(1, Allocator.TempJob);
private MyJob JobData = new MyJob();
private JobHandle handle;
private ulong r;
private void Start()
{
JobData.result = result;
handle = JobData.Schedule();
handle.Complete();
r = result[0];
}
private void Update()
{
if(r != 20)
{
Debug.Log("wait for seconds");
}
if (r != 0)
{
Debug.Log($"jobData result : {r}");
r = 0;
JobData.result = result;
handle = JobData.Schedule();
handle.Complete();
r = result[0];
}
go.transform.position += Vector3.forward * Time.deltaTime;
}
public struct MyJob : IJob
{
public NativeArray<ulong> result;
public void Execute()
{
result[0] = 1;
for(int i = 0; i < 20; i++)
{
result[0]++;
}
}
}
}
// 실행결과로는 wait for seconds와 jobData result : ?가 번갈아 출력되고, 게임 오브젝트가 움직이는 것을 확인해 볼 수 있다.