Unity Tips

Unity Entities - System에서 Collections(NativeArray, NativeList ...) Dispose함수를 Job 이후에 실행하는 방법

종잇장 2023. 7. 4. 22:57

Unity 2022.3.2f

Entities 1.0.11

 

 

ISystem 인터페이스에 함수들에는 SystemState를 인자로 받도록 되어있는데, state의 Dependency를 활용하면 쉽게 가능합니다.

public partial struct ECSExpGatherSystem : ISystem
{
	// ... 생략 ... //
    
    public void OnUpdate(ref SystemState state)
    {
    	// ... 생략 ... //
        
        var expCount = expQuery.CalculateEntityCount();
        var resultExp = new NativeArray<int>(expCount, Allocator.TempJob);
        var gatheringExpJobHandle = new GatheringExpJob()
        {
            ecb = ecb,
            deltaTime = SystemAPI.Time.DeltaTime,
            playerData = playerData,
            playerPosition = playerTransform.Position,
            resultExp = resultExp,
        };
        state.Dependency = gatheringExpJobHandle.ScheduleParallel(expQuery, state.Dependency);
        var playerGatherExpJobHandle = new PlayerGatherExpJob()
        {
            resultExp = resultExp,
        };
        state.Dependency = playerGatherExpJobHandle.ScheduleParallel(playerQuery, state.Dependency);
        state.Dependency = resultExp.Dispose(state.Dependency);
    }
}

위 코드에서는 명시적으로 ScheduleParallel 함수에 state.Dependency를 명시적으로 넣어줬는데 인자가 없는 함수에서는 내부적으로 state.Dependency를 참조하는 것으로 보입니다.

 

state.Dependency = collisionResultDataArray.Dispose(state.Dependency);

위 코드 처럼 Dispose함수를 Job Schedule 이후에 state.Dependency를 이용해 호출시켜주면, Job 실행 후에 실행되도록 등록됩니다.