Unity的ECS初学笔记+遇到的坑记录

我是直接在git上下载的ecs包:官方ECS的Git库

ECS主要用三个类来控制:

这个类应该直接绑定在我们的物体上:

 public class MoveAuthor : MonoBehaviour
    {
        class Baker : Baker<MoveAuthor>
        {
            public override void Bake(MoveAuthor authoring)
            {
                var entity = GetEntity(TransformUsageFlags.Dynamic);
                AddComponent<Move>(entity);
            }
        }

    }

其中的Move即为一个继承了IComponentData的接口:

   public struct Move : IComponentData
    {
        
    }

最后是system: 

public partial struct MovingSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        //这里先请求update绑定的move结构体
        state.RequireForUpdate<Move>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var dt = SystemAPI.Time.DeltaTime;
       
        foreach (var (transform, entity) in
                      SystemAPI.Query<RefRW<LocalTransform>>()
                          .WithAll<Move>() 
                          .WithEntityAccess())
        {
            // ValueRW returns a ref to the actual component value.
            // Add a rotation around the parent's Y axis.
            var pos = transform.ValueRO.Position;

            // This does not modify the actual position of the tank, only the point at
            // which we sample the 3D noise function. This way, every tank is using a
            // different slice and will move along its own different random flow field.
            pos.y = (float)entity.Index;

            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.ValueRW.Position += dir * dt * 5.0f;
            transform.ValueRW.Rotation = quaternion.RotateY(angle);
        }
    }
}

注意:绑定了MoveAuthor 的物体一定要放在Sub Sence下,不然MovingSystem 的update无法正常运行。

在MoveAuthor中,GetEntity(TransformUsageFlags.Dynamic)是需要Dynamic的,最开始我是使用的TransformUsageFlags.None,会导致物体无法正常移动。

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值