2 questions regarding IComponentData of unknown type.

  1. I have base class used in the editor which has an abstract method that should give me a component. For technical reasons I can’t specify the exact return type(these classes are stored in a [SerializeReference] List), so I believe I need to return the component as IComponentData.

How can I add this component to an entity? When I try to add with EntityManager, I get

  1. Given an unknown(but defined) IComponentData, how can I check if an entity has this component?

Example for #1:

public abstract class ConsiderationAuthoring {
    public string Description;

    public abstract IComponentData Convert();
}

public class ConsiderHealthAuthoring : ConsiderationAuthoring {
    public AnimationCurve Curve;
    public float Range;

    public override IComponentData Convert() {
        // Some code creating the component I need
    }
}

[CreateAssetMenu(menuName="IAUS/Action")]
public class ActionSO : ScriptableObject {
    [SerializeReference, SelectType(typeof(ConsiderationAuthoring))]
    public List<ConsiderationAuthoring> Considerations;

    // Example of adding component, just for testing
    public void OnEnable() {
        foreach(ConsiderationAuthoring consideration in Considerations) {
            var component = consideration.Convert();
            // ?
        }
    }
}

instead of sending an unknown IComponentData, try sending back the name of the ComponentType and pointer to bytes of the component data.

Then your conversion code could have a switch statement for each componentType, casting the byte* to whatever struct you need.

Overall, pretty hacky.

So, for flexibility sake I’d like to figure out a way to avoid switch unless absolutely necessary. From trying things out, I found if i do:

EntityManager manager = World.DefaultGameObjectInjectionWorld.EntityManager;

dynamic component = Consideration.Convert();
Entity entity = manager.CreateEntity();
manager.AddComponentData(entity, component);

It works, and the correct component type can be added and the field’s are correct. I never use dynamic so I’m curious, could this go horribly wrong? Why is this allowed?

Think I’ll just go with this: Combine components at runtime

The components I’m adding are actually supposed to be chunk components, so hopefully that works ok. Still wonder about dynamic and my second question though, can I use ComponentType or IIRC something about a ComponentType ID?