【Unity3D】ECS入门学习(五)共享组件 ISharedComponentData
using Unity.Entities;
using System;
//[GenerateAuthoringComponent] 无法生效 必须手动添加
public struct MyShareComponentData : ISharedComponentData, IEquatable<MyShareComponentData>
{
public int data;
public bool Equals(MyShareComponentData other)
{
return data == other.data;
}
public override int GetHashCode()
{
int tempHash = 0;
return tempHash ^= data.GetHashCode();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
public class ShareConvert : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddSharedComponentData<MyShareComponentData>(entity, new MyShareComponentData() { data = 1 });
}
}
一个继承于Monobehaviour脚本 Start方法执行如下代码:
//查询共享组件 缓存到数组
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityQuery query = entityManager.CreateEntityQuery(typeof(MyShareComponentData));
NativeArray<Entity> array = query.ToEntityArray(Allocator.TempJob);
//获取并修改 (默认是1) 实际上它会创建一个新的共享组件,并不会影响array[1]实体的组件,它还是保持1
//MyShareComponentData shareCom = entityManager.GetSharedComponentData<MyShareComponentData>(array[0]);
//shareCom.data = 5;
//entityManager.SetSharedComponentData(array[0], shareCom);
//与上方同理
entityManager.SetSharedComponentData(array[0], new MyShareComponentData() { data = 5 });
//移除
//entityManager.RemoveComponent<MyShareComponentData>(array[0]);
MyShareComponentData share1 = entityManager.GetSharedComponentData<MyShareComponentData>(array[0]);
MyShareComponentData share2 = entityManager.GetSharedComponentData<MyShareComponentData>(array[1]);
Debug.Log(share1.Equals(share2));
query.Dispose();
array.Dispose();
场景上创建2个空物体挂载如下脚本:
运行测试会发现如下图
仅有index=0的被修改为5,另一个不会,也就是说修改共享组件会生成一个新的组件,能让共享组件发挥作用就是不要修改内容,这样才会保持使用同一个。
共享组件使用AddSharedComponentData接口添加、SetSharedComponentData设置、GetSharedComponentData获取。