目前ECS分为两种,即HybridECS和PureECS
HybridECS是可以和MonoBehavior混合开发的,上手难度要比Pure小好多
PureECS则是纯ECS思路开发
以下为HybridECS的代码
Component:
1 2 3 4 5 6 7 8 9 |
using Unity.Entities; namespace Hybrid_ECS { public struct MovementComponent : IComponentData { public float moveSpeed; } } |
System:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using Unity.Entities; using Unity.Transforms; namespace Hybrid_ECS { public class MovementSystem : ComponentSystem { protected override void OnUpdate() { Entities.ForEach((ref Translation translation, ref MovementComponent moveComponentData) => { translation.Value.y += moveComponentData.moveSpeed * Time.DeltaTime; }); } } } |
Test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; namespace Hybrid_ECS { public class HyBridECSTest : MonoBehaviour { [SerializeField] GameObject cubePrefab; [SerializeField] int rowNum = 10; [SerializeField] int columnNum = 10; // Start is called before the first frame update private List<Entity> entities; void Start() { EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; Entity entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(cubePrefab, GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null)); entities = new List<Entity>(); for (int i = 0; i < rowNum; i++) { for (int j = 0; j < columnNum; j++) { Entity entityClone = entityManager.Instantiate(entityPrefab); Vector3 position = transform.TransformPoint(new float3(i - rowNum / 2, noise.cnoise(new float2(i, 2) * 0.3f), j - columnNum / 2)); entityManager.AddComponentData(entityClone, new Translation() { Value = position }); entityManager.AddComponentData(entityClone, new MovementComponent { moveSpeed = 1f }); entities.Add(entityClone); } } } private void Update() { if (Input.GetMouseButtonDown(0)) { EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; foreach (var entity in entities) { entityManager.SetComponentData(entity, new MovementComponent{moveSpeed = 1f}); } } if (Input.GetMouseButtonDown(1)) { EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; foreach (var entity in entities) { entityManager.SetComponentData(entity, new MovementComponent{moveSpeed = -1f}); } } } } } |
- 本文固定链接: http://www.u3d8.com/?p=2254
- 转载请注明: 网虫虫 在 u3d8.com 发表过