【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();
相关推荐
虾球xz4 小时前
游戏引擎学习第268天:合并调试链表与分组
c++·学习·链表·游戏引擎
Y3174294 小时前
Python Day23 学习
python·学习
song_ly0015 小时前
深入理解软件测试覆盖率:从概念到实践
笔记·学习·测试
DIY机器人工房5 小时前
[6-2] 定时器定时中断&定时器外部时钟 江协科技学习笔记(41个知识点)
笔记·stm32·单片机·学习·江协科技
海尔辛6 小时前
学习黑客5 分钟小白弄懂Windows Desktop GUI
windows·学习
烟雨迷8 小时前
Linux环境基础开发工具的使用(yum、vim、gcc、g++、gdb、make/Makefile)
linux·服务器·学习·编辑器·vim
@十八子德月生8 小时前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
qq_5982117579 小时前
Unity.UGUI DrawCall合批笔记
笔记·unity·游戏引擎
Clockwiseee9 小时前
文件上传总结
运维·服务器·学习·文件上传
苜柠10 小时前
Wpf学习片段
学习