Using ECS with Nested Gameobjects,

Im not sure if this will help but its a topic I started a while back and it,s about my learning ECS systems I would hope theres some useful information there.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Collections;
using Unity.Rendering;
using Unity.Transforms;
/*
Packages 
Collections
Hybrid Renderer 
Entities
*/


public struct HealthComponent : IComponentData {
    public float Value;
}

public class EntityClone : MonoBehaviour
{

    [SerializeField]
    public Mesh mesh;

    [SerializeField]
    public Material material;

      private EntityManager em;

      public int NumToCreate;

      public float Spacing;

    public void Start()
    {

        em = World.DefaultGameObjectInjectionWorld.EntityManager;

        EntityArchetype ea = em.CreateArchetype(
            typeof (Translation),
            typeof (LocalToWorld),
            typeof (HealthComponent),
            typeof (RenderMesh)
     
        );
        NativeArray<Entity> entityArray = new NativeArray<Entity>(NumToCreate, Allocator.Temp);
        em.CreateEntity(ea, entityArray);
        for(int i = 0; i < entityArray.Length; i++)
        {
         
            Entity entity = entityArray[i];

            em.SetComponentData(entity, new HealthComponent { Value = Random.Range(0f,1000f)});
            em.SetSharedComponentData(entity, new RenderMesh {
             
                mesh = mesh,
                material = material

            });
            em.SetComponentData(entity, new Translation{Value = new Unity.Mathematics.float3(Spacing * i,Spacing * i,Spacing * i) });
        }

        //Clean up the array as we do not need to keep it in memeory anymore.
        entityArray.Dispose();
    }
}
}

ECS Advice page-2#post-5157596

The above code allows you to drag a mesh and material and set the number of entities you want to spawn You can change the Random Position thing.

The main problem I have with ECS is trying to get my head round the fact that they are NOT Objects and how you can single out a reference (I know you can use an empty Component within the Entity itself and do Entities.ForEach((ref PlayerTag tag) => )

2 Likes