[5]Unity ECS 探路日记 官方Sample5

这个例子讲了如何把Mono的Prefab转换为Entiry的Prefab并且产生100*100个旋转的方块

README

此示例演示如何使用Prefab GameObject生成实体和组件。 场景产生了旋转立方体对的“场”。

##它显示了什么?

此示例使用HelloCube_02_IJobForEach中的组件和系统。

Unity.Entities提供GameObjectConversionUtility以将GameObject层次结构转换为其Entity表示。 使用此实用程序,您可以将预制件转换为实体表示,并使用该表示在需要时生成新实例。

当您实例化实体预制件时,整个预制件表示被克隆为一个组,就像基于GameObjects实例化预制件一样。

HelloSpawnMonoBehaviour类将Prefab转换为Start()方法中的Entity表示,然后实例化旋转对象的字段。

直奔主题 我们来看一下HelloSpawnMonoBehaviour.cs 并讲一下主要的代码

在Start方法的第一行 就把Prefab转换为了Entity的Prefab

// Create entity prefab from the game object hierarchy once
Entity prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, World.Active);

随后使用World.Active.EntityManager的 Instantiate方法实例化Entiry Prefab

最后用World.Active.EntityManager.SetComponentData方法设置了 物体的位置

上代码:

using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

namespace Samples.HelloCube_05
{
    public class HelloSpawnMonoBehaviour : MonoBehaviour
    {
        public GameObject Prefab;
        public int CountX = 100;
        public int CountY = 100;
    
        void Start()
        {
            // Create entity prefab from the game object hierarchy once
            Entity prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, World.Active);
            var entityManager = World.Active.EntityManager;
        
            for (int x = 0; x < CountX; x++)
            {
                for (int y = 0; y < CountX; y++)
                {
                    // Efficiently instantiate a bunch of entities from the already converted entity prefab
                    var instance = entityManager.Instantiate(prefab);
                
                    // Place the instantiated entity in a grid with some noise
                    var position = transform.TransformPoint(new float3(x * 1.3F, noise.cnoise(new float2(x, y) * 0.21F) * 2, y * 1.3F));
                    World.Active.EntityManager.SetComponentData(instance, new Translation {Value = position});
                }
            }
        }
    }    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章