Passing a List from Baker class to Entity-based Component

I have the following code snippet:

public class MyDataAuthoring : MonoBehaviour
{
    public List<int> ItemIds;
    public int value;

    private class Baker : Baker<MyDataAuthoring >
    {
        public override void Bake(MyDataAuthoring authoring)
        {
            Entity entity = GetEntity(TransformUsageFlags.Renderable);
            AddComponent(entity, new MyData{
                //Pass ItemIds
                value = authoring.value
            });
        }
    }
}
public struct MyData : IComponentData
{
    //Pass ItemIds List to some Blittable type
    public int value;
}

My aim is to pass ItemIds from MyDataAuthoring to MyData. How can I achieve this?

Are you familiar with DynamicBuffer and the IBufferElementData types?

I did have a brief look at it and this is what I came up with:

public class MyDataAuthoring : MonoBehaviour
{
    public List<int> ItemIds;
    public int value;

    private class Baker : Baker<MyDataAuthoring>
    {
        public override void Bake(MyDataAuthoring authoring)
        {
            DynamicBuffer<int> ids = new DynamicBuffer<int>();

            for(int i = 0; i < authoring.ItemIds.Count; ++i)
            {
                ids.Add(authoring.ItemIds[i]);
            }

            Entity entity = GetEntity(TransformUsageFlags.Renderable);
            AddComponent(entity, new MyData{
                value = authoring.value
            });
        }
    }
}
public struct MyData : IComponentData
{
    public DynamicBuffer<int> ItemId;
    public int value;
}

I’m obviously using it incorrectly, as I get this error on MyData.ItemId:
ArgumentException: Blittable component type 'MyData' on GameObject 'Interactable' contains a (potentially nested) pointer field. Serializing bare pointers will likely lead to runtime errors. Remove this field and consider serializing the data it points to another way such as by using a BlobAssetReference or a [Serializable] ISharedComponent. If for whatever reason the pointer field should in fact be serialized, add the [ChunkSerializable] attribute to your type to bypass this error.

And this on ids.Add:
NullReferenceException: Object reference not set to an instance of an object

Will need to do more reading up on DynamicBuffer. It’s definitely what I need.

Dynamic Buffers are not fields in IComponentData. They are a buffer-like parallel to IComponentData, where each element is an IBufferElementData. You create one in a baker via AddBuffer().

1 Like

There’s also FixedList in Unity.Collections that you can put in an IComponentData.

You have to be very careful about this, because it breaks if the contained type has entity or blob ref fields.

1 Like