How to use Generic type on DynamicBuffer

Hi everyone.

Why do mu code isn’t working and ask me for T to be a non-nullable type ? (On the Function name, and GetBuffer<T>)

public static class Helper {
        public static DynamicBuffer<T> EnsureHaveEmptyBuffer<T>(EntityManager entityManager, Entity entity, ComponentType componentType)
            where T : struct, IBufferElementData
        {
            if (!entityManager.HasComponent(entity, componentType))
                entityManager.AddComponent(entity, componentType);

            var buffer = entityManager.GetBuffer<T>(entity);
            buffer.Clear();
            return buffer;
        }

        public static DynamicBuffer<T> EnsureHaveEmptyBuffer<T>(EntityManager entityManager, Entity entity)
            where T : struct, IBufferElementData
        {
            return EnsureHaveEmptyBuffer<T>(entityManager, entity, ComponentType.ReadWrite<T>());
        }
}

I added struct to fix the issue, and have <T> the same “where” as GetBuffer but still have the issue ?!

You are asking in wrong forum section.
Head to Scripting ECS, or jobs forum section.

The correct constraint to use in most cases in ECS code is : unmanaged. This is more restrictive than : struct, because it ensures that the type only consists of unmanaged structs/primitives, and contains no managed references, all the way down.

2 Likes