SystemBase 및 Entities.ForEach 병렬 처리를 소개합니다.
1. "Scripts/Authoring" 폴더에 "TankAuthoring.cs"라는 이름의 새 C# 소스 파일을 만들고 다음 코드를 작성합니다.
using Unity.Entities;
class TankAuthoring : UnityEngine.MonoBehaviour
{
class TankBaker : Baker<TankAuthoring>
{
public override void Bake(TankAuthoring authoring)
{
AddComponent<Tank>();
}
}
}
// 포탑에서 했던 것처럼 탱크(큐브)를 식별하는 Tag Component를 만듭니다.
struct Tank : IComponentData
{
}
2. "Tank" GameObject에 "TankAuthoring" Component를 추가합니다.
3. "Scripts/Systems" 폴더에 "TankMovementSystem.cs"라는 이름의 새 C# 소스 파일을 만들고 아래 코드를 작성합니다.
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
// ISystem과 반대로 SystemBase 시스템은 class입니다. (ISystem은 interface)
// BurstCompile 적용되지 않으며 관리 코드를 사용할 수 있습니다.
partial class TankMovementSystem : SystemBase
{
protected override void OnUpdate()
{
// 아래의 Entities.ForEach는 (암시적으로) BurstCompile됩니다.
// 그리고 시간은 관리되는 유형(class)인 SystemBase의 멤버입니다.
// 이것은 거기에서 Time에 직접 접근하는 것이 불가능하다는 것을 의미합니다.
// 따라서 필요한 값(DeltaTime)을 로컬 변수에 복사해야 합니다.
var dt = SystemAPI.Time.DeltaTime;
// Entities.ForEach는 쿼리 처리에 대한 오래된 접근 방식입니다.
// 사용이 권장되지는 않지만 IFE와 기능 패리티를 얻을 때까지 편리합니다.
Entities
.WithAll<Tank>()
.ForEach((TransformAspect transform) =>
{
// 이것은 ForEach에 매개변수로 전달되는 람다식입니다.
var pos = transform.LocalPosition;
// Unity.Mathematics.noise는 여러 유형의 노이즈 함수를 제공합니다.
// 여기서는 클래식 Perlin 노이즈(cnoise)를 사용합니다.
// Perlin 노이즈에서 흐름 필드를 생성하기 위해 취한 접근 방식은 여기에 자세히 설명되어 있습니다.
// https://www.bit-101.com/blog/2021/07/mapping-perlin-noise-to-angles/
var angle = (0.5f + noise.cnoise(pos / 10f)) * 4.0f * math.PI;
var dir = float3.zero;
math.sincos(angle, out dir.x, out dir.z);
transform.LocalPosition += dir * dt * 5.0f;
transform.LocalRotation = quaternion.RotateY(angle);
// Entities.ForEach 시퀀스의 마지막 함수 호출은
// Run(메인 스레드), Schedule(단일 스레드, 비동기) 또는 ScheduleParallel(다중 스레드, 비동기) 중
// 코드 실행 방법을 제어합니다.
// Entities.ForEach는 기본적으로 작업 생성기이며 이를 통해 병렬 작업을 매우 쉽게 생성할 수 있습니다.
// 불행하게도 이것은 복잡성 비용과 이상한 임의의 제약을 수반하므로 더 명시적인 접근 방식이 선호됩니다.
// 이러한 명시적 접근 방식(IJobEntity)은 이 Tutorial의 뒷부분에서 다룹니다.
}).ScheduleParallel();
}
}
4. 플레이 모드로 들어가면 탱크가 흐름에 따라 움직이기 시작해야 합니다.
5. 플레이 모드를 종료합니다.
'Unity Entities Tutorial' 카테고리의 다른 글
Unity Entities 1.0.0 Tutorial - Step 5. Cannon ball movement (0) | 2023.01.29 |
---|---|
Unity Entities 1.0.0 Tutorial - Step 4. Cannon Balls (1) | 2023.01.28 |
Unity Entities 1.0.0 Tutorial - Step 2. Turret Rotation (0) | 2023.01.28 |
Unity Entities 1.0.0 Tutorial - Step 1. Authoring Scene (0) | 2023.01.28 |
Unity Entities 1.0.0 Tutorial - Step 0 (0) | 2023.01.24 |