C#/Unity/Hybrid ECS - Trying to convert GameObject into ECS Entity

2.2k views Asked by At

I am Using Unity 2019.2.14f.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;

public class GameSystem : MonoBehaviour
{
    public GameObject player;
    public int spawnNumber;
    public bool useECS;
    private EntityManager manager;
    // Start is called before the first frame update
    void Start()
    {
        manager = World.Active.EntityManager;
        if (useECS)
        {
            SpawnECS(player);
        }
            else
        {
            for (int i = 0; i <= spawnNumber; i++)
            {
                Spawn(player);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void Spawn(GameObject unit)
    {
        float x = Random.Range(5, 249);
        float y = 0f;
        float z = Random.Range(5, 249);
        float rx = 0f;
        float ry = Random.Range(1, 180);
        float rz = 0f;
        Instantiate(unit, new Vector3(x, y, z), Quaternion.Euler(rx,ry,rz));
    }

    private void SpawnECS(GameObject unit)
    {
        float x = Random.Range(5, 249);
        float y = 0f;
        float z = Random.Range(5, 249);
        float rx = 0f;
        float ry = Random.Range(1, 180);
        float rz = 0f;
        NativeArray<Entity> players = new NativeArray<Entity>(spawnNumber, Allocator.Temp);
        manager.Instantiate(unit, players);
        players.Dispose();
    }
}

This is the prefab which I am instantiating:

enter image description here

When I select on my GameSystem component useECS to be true I can see it is creating enteties into my entity debugger. Take a look:

enter image description here

So as you can see Entities are created. However when I inspect one Entity here is what I see: enter image description here

As you can see Components are not converted. Where is my mistake? How can I create visible entity out of GameObhject Prefab or use the so-called Hybrid ECS method?

1

There are 1 answers

1
Andrew Łukasik On
NativeArray<Entity> players = new NativeArray<Entity>( 3 , Allocator.Temp );

Is equivalent to writing :

var players = new GameObject[]{ new GameObject() , new GameObject() , new GameObject() };

It's a list of prefab entities, that are completely empty. This is why spawning that list will give N amount of default entities.

What to should do instead is to convert that player GameObject to an entity prefab and instantiate that entity prefab N times (or populate that NativeArray with set of entity prefabs)

Entity entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy( gameObjectPrefab );