【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();
相关推荐
charlie1145141912 小时前
从0开始使用面对对象C语言搭建一个基于OLED的图形显示框架(协议层封装)
c语言·驱动开发·单片机·学习·教程·oled
马船长3 小时前
[BSidesCF 2020]Had a bad day1
学习
黄交大彭于晏3 小时前
三端回链增加截图功能
学习
linwq83 小时前
设计模式学习(二)
java·学习·设计模式
Fhd-学习笔记4 小时前
《大语言模型》综述学习笔记
笔记·学习·语言模型
Dr.勿忘5 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
简知圈5 小时前
【04-自己画P封装,并添加已有3D封装】
笔记·stm32·单片机·学习·pcb工艺
YxVoyager5 小时前
GAMES101学习笔记(五):Texture 纹理(纹理映射、重心坐标、纹理贴图)
笔记·学习·图形渲染
存储服务专家StorageExpert5 小时前
答疑解惑:如何监控EMC unity存储系统磁盘重构rebuild进度
运维·unity·存储维护·emc存储
徐某人..6 小时前
ARM嵌入式学习--第十天(UART)
arm开发·单片机·学习·arm