文章目录
- 一.简介
- 二.例子
一.简介
在之前的学习中我们发现Entity不能挂载相同的组件的.
当我们需要用相同的组件时则可以使用.IBufferElementData接口
动态缓冲区组件来实现
二.例子
1.创建IBufferElementData组件
using Unity.Entities;
using UnityEngine;
//[GenerateAuthoringComponent]
public struct BufferComponent8 : IBufferElementData
{public int dataA;public int dataB;
}
2.创建管理组件
using Unity.Entities;
using UnityEngine;
public class Authoring8 : MonoBehaviour, IConvertGameObjectToEntity
{public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem){DynamicBuffer<BufferComponent8> tempBuffer = dstManager.AddBuffer<BufferComponent8>(entity);tempBuffer.Add(new BufferComponent8() { dataA = 1, dataB = 100 });tempBuffer.Add(new BufferComponent8() { dataA = 2, dataB = 101 });tempBuffer.Add(new BufferComponent8() { dataA = 3, dataB = 102 });}
}
3.在场景中管理组件
4.运行后看到多个相同组件挂到了同一个实体
5.查询组件值
using Unity.Collections;
using Unity.Entities;
using UnityEngine;
public class Test8 : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){EntityQuery tempEntityQuery = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntityQuery(typeof(BufferComponent8));NativeArray<Entity> tempEntites1 = tempEntityQuery.ToEntityArray(Allocator.TempJob);DynamicBuffer<BufferComponent8> tempBuffer = World.DefaultGameObjectInjectionWorld.EntityManager.GetBuffer<BufferComponent8>(tempEntites1[0]);Debug.Log(tempBuffer[0].dataA);tempEntites1.Dispose();}
}
6.编译组件
foreach (var item in tempBuffer)
{Debug.Log(item.dataA);
}
7.插入组件
tempBuffer.Insert(0, new BufferComponent8() { dataA = 999, dataB = 878 });