Video games are a serious business. Ask anyone who plays or designs them! A lot goes into creating these games, including various utilities, architecture, and coding. That's why today we are covering Entity Component Systems. Some writers insert hyphens between each word, but we won't be doing that, although we will often refer to the term by its commonly used acronym of ECS.

This article introduces you to the Entity Component System, including what it is, its pros and cons, examples, how to create ECS hierarchies, and much more.

Let’s begin our guide with some definitions.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Is an Entity Component System?

The Entity Component System is an architectural pattern often used in video game development. It facilitates code reusability by separating the data from the behavior. In addition, ECS obeys the "composition over inheritance principle," providing improved flexibility and helping developers identify entities in a game's scene where all the objects are classified as entities.

Frameworks often enable Entity Component Systems, and the term "ECS" is frequently used to illustrate a specific design pattern implementation.

An ECS consists of the following elements:

  • It has unique identifiers known as entities.
  • It contains plain datatypes without behavior known as components.
  • It has systems, defined as functions that are matched with entities that have a particular set of components.
  • Entities may contain zero or more components.
  • Entities can dynamically change components.

So, an ECS is an architecture that focuses on data and separates data/components, identity/entities, and behavior/systems. These characteristics make it a natural fit for video game design.

Now, let’s break down the term into separate parts and identify them better.

What Is Defined as an Entity?

An entity represents one "thing" in a video game, a distinct object representing an actor in a simulated space, typically expressed as a unique integer value. For example, if you’re playing Skyrim, all the tangible, visible “things” in the game’s universe are entities. They contain no actual data or behaviors.

What’s the Definition of a Component?

Components are datatypes consisting of a unique behavior assigned to an entity. They are reusable modules that programmers attach to the entities, providing behavior, functionality, and appearance, forming an entity.

For example, a sword and sorcery game programmer could build a magic sword entity by gathering these components:

  • A material component, such as "shininess," influences the sword's appearance
  • A weight component measures “pounds” to determine the sword’s overall weight
  • A damage component that influences how practical of a weapon the sword is

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

What Is Considered the System?

Systems iterate components to perform low-level functions like performing physics calculations or rendering graphics. Systems provide global scope, services, and management for component classes. It’s basically the logic that operates on the components.

For example, a camera system manages every entity with a camera component, controlling which camera is active.

What’s a Composition?

Compositions allow developers to attach more components to add additional functionalities, behavior, or appearance.

The Advantages of ECS

Here’s why Entity Component Systems are a benefit to programmers:

  • Programmers can use ECS to create shorter, less complicated code
  • It offers a clean design that employs decoupling, encapsulation, modularization, and reusability methods
  • It lets programmers mix reusable parts, providing better flexibility when defining objects
  • It features very flexible emergent behavior
  • It offers an architecture for both 3D and VR development, allowing you to build the latter application in terms of complexity
  • It allows non-techies to script by behavior
  • It’s an easy choice for unit testing and mocking
  • You can switch components with mocked components at run-time
  • It helps you to add or bolster new features
  • It’s a friendly method for multi-threading and parallel processing
  • It helps programmers separate data from the functions that can act on it.

The Disadvantages of Using ECS

Of course, every tool has its downside. Here’s are things about ECS that aren’t as great:

  • ECS is not very well known. Most people haven’t even heard of it. That can pose problems for collaboration.
  • It’s not as concretely defined as other patterns, like Model-View-Controller (MVC).
  • It’s challenging to apply correctly, and it’s easy to misuse. As a result, programmers need to think more about how to design good components.
  • ECS requires programmers to write many small systems which can potentially be used in vast numbers of entities. This method results in a risk of writing very inefficient code

Entity Component System Example

This illustration, provided by Docs.unity3d, shows an example of ECS architecture and how the parts all work together.

Entity_Component_System

Data flow in ECS

We can break down the ECS data flow into the following steps:

  • System: The system listens to outside events and publishes updates to the components.
  • Component: The components listen to system events, then update their state.
  • Entity: The entity gains behavior through the changes in component states.

So, a gamer presses the “right arrow” key while adventuring in a fantasy world. The player input system detects the gamer’s key press and updates the motion component. The motion system activates and “sees” that the entity’s motion is to the right, so it applies the Physics force accordingly. Then, the render system takes over and reads the entity’s current position, drawing it according to its new spatial definition.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Why Is ECS Used?

We’ve already touched upon the advantages of ECS, but there are four reasons why game developers like using it:

  • First, it can support many game objects
  • Second, its code is more reusable
  • Third, it allows a more dynamic coding style
  • Fourth, it lets developers extend/add new features

How Is ECS Different From OOP?

Some people consider ECS an alternative to Object Oriented Programming, otherwise known as OOP. Although the two share some overlapping similarities, there are four key differences between them:

  • OOP encourages data encapsulation while ECS promotes exposed plain old data (POD) objects
  • OOP considers inheritance a first-class citizen, while ECS considers composition a first class
  • OOP colocates data with behavior, but ECS separates the data from behavior
  • OOP Object instances are single static, and entities may dynamically change multiple components

How Is ECS Different From Entity-Component Frameworks?

Although they share two-thirds of the same name, ECS and Entity-Component Frameworks aren’t the same. EC frameworks, like the ones usually found in game engines, are like ECS in that they allow entity creation and component composition.

But in EC, components are classes that have both data and behavior. Also, behavior is executed directly on the component. Here’s what a simple EC framework looks like, courtesy of GitHub:

class IComponent {

public:

virtual void update() = 0;

};

class Entity {

vector<IComponent*> components;

public:

void addComponent(IComponent *component);

void removeComponent(IComponent *component);

void updateComponents();

}; 

Is ECS a Lower Level of Abstraction?

Not really. Although several ECS designs may leverage low-level machine optimizations, an ECS’s written code doesn’t have to be lower or higher than other approaches.

Does ECS Require Writing More Code?

The answer really depends on the ECS framework and what kind of engine you’re using. When you integrate an ECS framework with an engine, you can get pretty compact and concise code that’s sometimes shorter than the non-ECS alternatives.

But when your ECS isn’t integrated with an engine, you will need additional glue-code to make a bridge between the native engine types and the ECS. This procedure can cause an application to write more code.

In the final analysis, though, any time spent writing ECS code is typically offset by the time savings you get from having a more maintainable codebase.

Is ECS Fast?

As a rule, yes, although it depends on what's being measured and the ECS implementation itself because different implementations result in different tradeoffs. So, for example, an operation that's slow in one framework could be extremely fast in another.

In terms of speed, ECS implementations are typically good at dynamically changing components at run-time and linearly querying and iterating entity sets. On the other hand, ECS implementations fall short in speed when executing queries or operations that need highly specialized data structures like spatial structures and binary trees.

But you can get the most out of your ECS if you familiarize yourself with the implementation’s tradeoffs and leverage its design.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

Is ECS Code More Reusable?

Yes, because an ECS’s behaviors are matched with a set of components, not tightly coupled with a class like in OOP. Since behaviors aren’t tied to one class, they can be used across different classes of entities.

Furthermore, programmers can introduce new systems at any stage of development. The systems will get automatically matched with any new or existing entities that contain the right components.

Is ECS Good for Multi-threading?

Usually, yes, because the separation of data and behavior means it’s easier to identify individual systems, their dependencies, and how the developer should schedule them.

Can ECS Be Used Outside of Gaming?

Yes, it can and has been used in non-gaming projects.

How Do You Create a Hierarchy in ECS?

Here’s an approach you can use to create a hierarchy in an Entity Component System, coding courtesy of Github.

// Store the parent entity on child entities

struct Parent {

entity parent;

}; 

// Store all children of a parent in a component with a vector

struct Children {

vector<entity> children;

}; 

// Store children in linked list

struct ChildList {

entity first_child; // First child of entity

entity prev_sibling; // Previous sibling

entity next_sibling; // Next sibling

}; 

How Do You Store Spatial Data in ECS?

Spatial data structures use layouts that don’t match up well with the typical ECS layout. However, you can create a query that iterates the relevant entries, storing them in spatial structures at either the start or end of each frame.

Summarize and Review

Here are the salient takeaways:

  • Entity-Component–Systems (ECS) is an architectural pattern
  • An entity is a distinct object representing an actor in a simulated space
  • A component is defined as a singular behavior that’s ascribed to an entity
  • A system iterates many components so they can perform low-level functions like pathfinding, rendering graphics, or performing physics calculations
  • A composition is an element to which programmers can attach more components, adding behaviors, additional appearance, or functionality
  • You can use an ECS pattern to create shorter, less complicated code
  • ECS isn’t as concretely defined as other patterns like MVC
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Do You Want to Learn Coding?

If you want to get involved in a career that provides ample rewards and long-term job security, today's commercial sector is experiencing continued demand for more full stack developers.

Simplilearn’s Caltech Coding Bootcamp gives you a valuable understanding of front-end, middleware, and back-end Java web developer technologies. The course, held in conjunction with Caltech’s Center for Technology and Management Education, uses hands-on training and phase-end and capstone projects to train you how to build end-to-end applications, store data using MongoDB, test and deploy code, and many more valuable and marketable skills.

So, if you want a new career in an exciting field with lots of growth potential or are just looking for a convenient and effective way to upskill, visit Simplilearn and see how their courses can open new doors. Check out Simplilearn today!

About the Author

John TerraJohn Terra

John Terra lives in Nashua, New Hampshire and has been writing freelance since 1986. Besides his volume of work in the gaming industry, he has written articles for Inc.Magazine and Computer Shopper, as well as software reviews for ZDNet. More recently, he has done extensive work as a professional blogger. His hobbies include running, gaming, and consuming craft beers. His refrigerator is Wi-Fi compliant.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors