How do I 'add' a monobehavior to an Entity?

I know that Monobehaviors can be associated with an Entity using the conversion tool. I am trying to do it manually without success.

code

using UnityEngine;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;

public class PolygonCreateLineRendererSystem : SystemBase
{

    EndSimulationEntityCommandBufferSystem m_EndSimulationEcbSystem;
    protected override void OnCreate()
    {
        base.OnCreate();
        m_EndSimulationEcbSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
    }


    protected override void OnUpdate()
    {
        //var ecb = m_EndSimulationEcbSystem.CreateCommandBuffer();
        Entities
            .WithoutBurst()
            .WithAll<Polygon, PolygonCreateLineRendererTag>()
            .ForEach((Entity entity, DynamicBuffer<PolygonPoint> buffer) => {
                var lr = new LineRenderer();
                lr.positionCount = buffer.Length;
                for(var i = 0; i < buffer.Length; i++)
                {
                    Debug.Log(buffer[i].Value);
                    lr.SetPosition(i, buffer[i].Value);
                }
                //ecb.SetComponent(entity, lr);
                World.EntityManager.SetComponentData<LineRenderer>(entity, lr);
                World.EntityManager.RemoveComponent<PolygonCreateLineRendererTag>(entity);

                Debug.Log("PolygonCreateLineRendererSystem hit!");
            })
            .Run();
            //.Schedule();
            //m_EndSimulationEcbSystem.AddJobHandleForProducer(this.Dependency);
    }
}

There is a method on EntityManager called AddObject or something like that

You should never do new SomeMonoBehabiour(), this is not how they work.

You have two options here:

A. Do that at conversion time using AddHybridComponent, which has its own limitations
B. Create an empty GameObject to be the container, doing an AddComponent() on it, then do EntityManager.AddComponentObject to link the entity to it. Just be aware that destroying the GameObject will destroy the LineRenderer, but destroying the Entity will not destroy the LineRenderer or the GameObject automatically for you.

Sample codes:

// option A
public class HybridLineRendererAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
    public LineRenderer Value;

    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        conversionSystem.AddHybridComponent(Value);
    }
}

// option B
LineRenderer value = new GameObject($"Entity {entity} Container").AddCompoment<LineRenderer>();
EntityManager.AddComponentObject(entity, value);
1 Like