欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 【Unity3D】ECS入门学习(二)实例化预制体

【Unity3D】ECS入门学习(二)实例化预制体

2025/4/21 3:29:10 来源:https://blog.csdn.net/qq_39574690/article/details/144764184  浏览:    关键词:【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);});}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词