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

组件继承于IBufferElementData,可以让一个实体拥有多个相同的组件。

cs 复制代码
using Unity.Entities;

public struct MyBuffComponentData : IBufferElementData
{
    public int num;
}
cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
public class BuffComponentConvert : MonoBehaviour, IConvertGameObjectToEntity
{
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        DynamicBuffer<MyBuffComponentData> bufferList = dstManager.AddBuffer<MyBuffComponentData>(entity);
        bufferList.Add(new MyBuffComponentData() { num = 1 });
        bufferList.Add(new MyBuffComponentData() { num = 2 });
    }
}

使用AddBuffer<组件类>(entity)添加缓存区组件,返回的是一个动态缓存区对象<组件类>

然后逐个创建和添加到动态缓存区对象里去就完成了对实体添加多个相同组件。

继承于Monobeahviour.cs脚本直接Start方法执行如下代码:

正常通过query的方式查询获取组件的实体数组,我们只有1个所以直接取array[0]实体对象,

使用EntityManager对象GetBuffer<组件类>(array[0])获取动态缓存区对象,它是一个列表,可以分别对它进行索引获取值输出,插入,遍历等操作。

cs 复制代码
//(7)缓存区组件
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityQuery query = entityManager.CreateEntityQuery(typeof(MyBuffComponentData));
NativeArray<Entity> array = query.ToEntityArray(Allocator.TempJob);
DynamicBuffer<MyBuffComponentData> bufferList = entityManager.GetBuffer<MyBuffComponentData>(array[0]);
Debug.Log(bufferList[0].num);

//末尾插入        
bufferList.Insert(bufferList.Length, new MyBuffComponentData() { num = 3 });
Debug.Log(bufferList[2].num);

//首部插入
bufferList.Insert(0, new MyBuffComponentData() { num = 4 });

//遍历组件
foreach (var v in bufferList)
{
    Debug.Log(v.num);
}

//销毁查询对象和数组        
query.Dispose();
array.Dispose();
相关推荐
yuxb735 小时前
Docker学习笔记(二):镜像与容器管理
笔记·学习·docker
LFly_ice5 小时前
学习React-9-useSyncExternalStore
javascript·学习·react.js
gmmi6 小时前
嵌入式学习 51单片机(3)
单片机·学习·51单片机
楼田莉子7 小时前
C++算法专题学习——分治
数据结构·c++·学习·算法·leetcode·排序算法
励志不掉头发的内向程序员9 小时前
C++进阶——继承 (1)
开发语言·c++·学习
悠哉悠哉愿意9 小时前
【数学建模学习笔记】机器学习分类:随机森林分类
学习·机器学习·数学建模
悠哉悠哉愿意9 小时前
【数学建模学习笔记】机器学习分类:KNN分类
学习·机器学习·数学建模
四谎真好看10 小时前
Java 学习笔记(进阶篇2)
java·笔记·学习
程序猿炎义10 小时前
【NVIDIA AIQ】自定义函数实践
人工智能·python·学习
小陈phd10 小时前
高级RAG策略学习(四)——上下文窗口增强检索RAG
人工智能·学习·langchain