【Unity3D】ECS入门学习(七)缓存区组件 IBufferElementData ...

打印 上一主题 下一主题

主题 990|帖子 990|积分 2970

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
组件继承于IBufferElementData,可以让一个实体拥有多个雷同的组件。
  1. using Unity.Entities;
  2. public struct MyBuffComponentData : IBufferElementData
  3. {
  4.     public int num;
  5. }
复制代码
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Unity.Entities;
  5. public class BuffComponentConvert : MonoBehaviour, IConvertGameObjectToEntity
  6. {
  7.     public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
  8.     {
  9.         DynamicBuffer<MyBuffComponentData> bufferList = dstManager.AddBuffer<MyBuffComponentData>(entity);
  10.         bufferList.Add(new MyBuffComponentData() { num = 1 });
  11.         bufferList.Add(new MyBuffComponentData() { num = 2 });
  12.     }
  13. }
复制代码
使用AddBuffer<组件类>(entity)添加缓存区组件,返回的是一个动态缓存区对象<组件类> 
然后逐个创建和添加到动态缓存区对象里去就完成了对实体添加多个雷同组件。
继承于Monobeahviour.cs脚本直接Start方法实行如下代码:
正常通过query的方式查询获取组件的实体数组,我们只有1个所以直接取array[0]实体对象,
使用EntityManager对象GetBuffer<组件类>(array[0])获取动态缓存区对象,它是一个列表,可以分别对它举行索引获取值输出,插入,遍历等操纵。
  1. //(7)缓存区组件
  2. EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
  3. EntityQuery query = entityManager.CreateEntityQuery(typeof(MyBuffComponentData));
  4. NativeArray<Entity> array = query.ToEntityArray(Allocator.TempJob);
  5. DynamicBuffer<MyBuffComponentData> bufferList = entityManager.GetBuffer<MyBuffComponentData>(array[0]);
  6. Debug.Log(bufferList[0].num);
  7. //末尾插入        
  8. bufferList.Insert(bufferList.Length, new MyBuffComponentData() { num = 3 });
  9. Debug.Log(bufferList[2].num);
  10. //首部插入
  11. bufferList.Insert(0, new MyBuffComponentData() { num = 4 });
  12. //遍历组件
  13. foreach (var v in bufferList)
  14. {
  15.     Debug.Log(v.num);
  16. }
  17. //销毁查询对象和数组        
  18. query.Dispose();
  19. array.Dispose();
复制代码
 




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

何小豆儿在此

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表