[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});
                }
            }
        }
    }    
}

 

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