Problem Writing to CommandBuffer in Extension Method

I’m unable to write to the default CommandBuffer PostUpdateCommands in a ComponentSystem inside an extension method.

I’m wrapping this type of action (adding a State), in an extension method - SetState().

PostUpdateCommands.SetSharedComponent(salesOrder, new SalesOrderState { State = SalesOrderStates.WorkOrder });

// Extension Method

public static class EntityCommandBufferExtensions {
    public static void SetState<TSharedComponent, TState>(this EntityCommandBuffer buffer, Entity entity, TState state)
         where TSharedComponent : struct, ISharedComponentData where TState : Enum {
        
        var stateObject = Activator.CreateInstance<TSharedComponent>();
        var stateField = typeof(TSharedComponent).GetField("State");
        stateField.SetValue(stateObject, state);
        buffer.SetSharedComponent(entity, stateObject);
    }
}

I use it like this:

PostUpdateCommands.SetState<SalesOrderState, SalesOrderStates>(salesOrder, SalesOrderStates.WorkOrder);

The code runs, but fails silently - the new state isn’t being updated.

Not an answer to your question, but you don’t need to use reflection/activator to create and set your instance. (Does reflection work in burst? Could be your issue)

var stateObject = default(TSharedComponent); // or new TSharedComponent()
startObject.State = state;

Thanks for the “default(T)”. Using “new” won’t work because inside the generic class you can’t use “new” unless T has the new() generic constraint. You can’t put “where new ()” on a struct, only a class.

Yes in a generic you need either the new() OR struct constraint to create a new instance as structs always have an empty constructor (hence new() makes no sense as it’s implicit).

So new TSharedComponent() works fine. I even tested it before I posted originally just to confirm my knowledge (though my ide recommends changing to default).

You’re right. I dumb-guy-typo tried to “new” my enum “new TState()”. lol