I'm trying to figure out how to implement a simple ECS with an Archetype approach, similar to what Unity's ECS uses.

An archetype is just a category for entities that have a specific set of components.

Let's say I had three components, A, B, and C, and I had the following systems:

  • System 1 (Archetype requires component A)
  • System 2 (Archetype requires components A and B)
  • System 3 (Archetype requires components A and C)
  • System 4 (Archetype requires components A, B, and C)

Because components could be added and removed from entities on the fly, an entity switches archetypes whenever a component is added or removed.

I'm not quite sure what these archetype collections are supposed to look like. They must be arrays of some kind, but I'm not sure how to store and organize components in them that belong to a specific entity.

My question is, what would this look like in pure, vanilla C# code?

And could generics also help with this?


Those Archetypes are IEnumerable<TComponentKind>, where TComponentKind is what you use to identify components. You can, of course, do better than that. For example, they could be TComponentKind[], or HashSet<TComponentKind>. TComponentKind could be string, Type or even int (and you use bit flags to identify components, in which case the Archetype is also int). Or you might come with something else. That depends on how you implement your ECS.

I have a toy ECS that should give you some idea of how to go about this: https://github.com/theraot/Theraot.ECS - You may download the code an play with it. Please read design decisions on the readme. After all, you are going to have to make your own take on those decisions for your custom ECS.

My toy ECS has the particular quirk that it lets you provide an implementation for custom TComponentKind. Which is likely not something you want in a ECS you use in production. But it means that the code is rather agnostic to that decision, which - I hope - makes for a good case study.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.