【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();
相关推荐
行思理12 分钟前
Docker 应该如何学习 分四个阶段
学习·docker·容器
大山同学24 分钟前
Blender学习-基础移动
数码相机·学习·blender
电子云与长程纠缠27 分钟前
Blender入门学习05 - 材质
学习·blender·材质
机器学习之心1 小时前
PSO-Transformer-BiLSTM分类预测/故障诊断,优化参数为注意力机制头数、学习率、正则化系数、隐藏层单元,图很多,包括分类效果图,混淆矩阵图
学习·分类·transformer·pso-transformer
摘星编程2 小时前
【成长纪实】HarmonyOS Next学习地图:新手避坑指南与核心知识点拆解
学习·华为·harmonyos·鸿蒙开发
yi碗汤园5 小时前
【一文了解】八大排序-冒泡排序、选择排序
开发语言·前端·算法·unity·c#·1024程序员节
deng-c-f5 小时前
Linux C/C++ 学习日记(32):协程(二):Ntyco源码解析
学习·协程·ntyco
Voyager_46 小时前
算法学习记录08——并归的应用(LeetCode[315])
学习·算法·leetcode
deng-c-f7 小时前
Linux C/C++ 学习日记(35):协程(五):同步、多线程、多协程在IO密集型场景中的性能测试
学习·线程·协程·同步·性能
Webb Yu7 小时前
加密货币学习路径
学习·区块链