【Unity3D】ECS入门学习(二)实例化预制体
创建Cube预制体,挂载脚本如下
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
/// <summary>
/// 将物体转化实体脚本类
/// 并且转化时进行对实体entity添加组件PrintTestComponentData
/// 同时将helloworld参数传递到组件中
///
/// 我们需要将这个物体挂载到随便一个物体上,即利用Monobehaviour周期去创建一个实体,并且这个实体带有组件PrintTestComponentData
/// 它只会创建1个
/// </summary>
public class PrintTestConvert : MonoBehaviour, IConvertGameObjectToEntity
{
//public float num;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
//dstManager.AddComponentData(entity, new PrintTestComponentData() {
// num = num
//});
dstManager.AddComponentData(entity, new RotationEulerXYZ());
}
}
创建空物体挂载脚本如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
public class ECSCubePrefabCreator : MonoBehaviour
{
public int num = 10;
public float interval = 1;
public GameObject cubePrefab;
void Start()
{
GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
Entity tempEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(cubePrefab, settings);
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
Translation translation = new Translation();
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
Entity tempCube = entityManager.Instantiate(tempEntityPrefab);
translation.Value.x += interval;
entityManager.SetComponentData(tempCube, translation);
}
translation.Value.x = 0;
translation.Value.y += interval;
}
}
}
注意:如果发现位置没生效,那肯定是有ComponentSystem获取到了实体并持续修改位置。如下代码,让系统不生效即可,加上[DisableAutoCreation]特性
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
/// <summary>
/// 系统是class,ComponentSystem是最基础的组件系统基类
/// 使用系统从全局实体遍历筛选出带有<PrintTestComponentData>组件的实体
/// </summary>
[DisableAutoCreation]
public class PrintTestSystem : ComponentSystem
{
protected override void OnUpdate()
{
Entities.ForEach((ref RotationEulerXYZ com, ref Translation translation) =>
{
//Debug.Log(com.helloworld);
//Debug.Log(com.num);
//com.Value = new float3(2, 2, 2);
com.Value = new float3(0, 45, 0);
translation.Value = new float3(3, 3, 3);
});
}
}