【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个所以直接取array0实体对象,

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

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();
相关推荐
织码weavecodes1 小时前
培训平台部署备份与容灾:从三服务交付到可恢复运行
大数据·学习·开源软件
JWASX3 小时前
Java 转 go 学习 - 类型转换
学习·golang
淡海水4 小时前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
小淮AI5 小时前
在职医生备考主治医师,我的资料搭配思路
学习
AOI小白新手上路6 小时前
韦东山《ARM 架构与编程》基于I.MX6ULL 3-1 硬件知识_LED 原理图 · 学习笔记
arm开发·学习·架构
传奇开心果编程6 小时前
【现代声明式UI学与练】第1课 从命令式UI到声明式UI
学习·flutter·ui·swiftui·react·android jetpack
小贺儿开发7 小时前
Unity 文物新生 会讲故事的文物展墙
人工智能·科技·unity·ai·视频·互动·演示
老王爱玩车8 小时前
工具函数——清空输入缓冲区
c语言·开发语言·学习
JWASX10 小时前
Java 转 go 学习 - 函数(1)
学习·golang
sunshine22 girl10 小时前
Java学习五 面向对象高级5 内部类3-静态内部类和局部内部类(了解)
java·学习