ECS Framework for Unity Game Engine and .Net Platform
ECS Framework for Unity Game Engine and .Net Platform
Key points for people familiar with other ECS frameworks:
English version: Migration Guide
Russian version: Гайд по миграции
Minimal required Unity Version is 2020.3.*
Requires Git for installing package.
Requires Tri Inspector for drawing the inspector.
Open Unity Package Manager and add Morpeh URL. ⭐ Master: https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh
Stage: https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh#stage-2024.1
️ Tag: https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh#2024.1.1
NuGet package URL: https://www.nuget.org/packages/Scellecs.Morpeh
An identifier for components, which does not store any data but can be used to access components. Logically, it is similar to a GameObject in Unity, but an Entity does not store any data itself.
It is a value type, and is trivially copyable. Underlying identifiers (IDs) are reused, but each reused ID is guaranteed to have a new generation, making each new Entity unique.
…Components are types which store components data. In Morpeh, components are value types for performance purposes.
public struct HealthComponent : IComponent {
public int healthPoints;
}Types that process entities with a specific set of components.
Entities are selected using a filter.
All systems are represented by interfaces.
public class HealthSystem : ISystem {
public World World { get; set; }
private Filter filter;
private Stash healthStash;
public void OnAwake() {
this.filter = this.World.Filter.With().Build();
this.healthStash = this.World.GetStash();
}
public void OnUpdate(float deltaTime) {
foreach (var entity in this.filter) {
ref var healthComponent = ref healthStash.Get(entity);
healthComponent.healthPoints += 1;
}
}
public void Dispose() {
}
}All systems types:
IInitializer - has OnAwake and Dispose methods only, which is convenient for executing startup logicISystem - main system that executes every frame in Update. Used for main game logic and data processingIFixedSystem - system that executes in FixedUpdate with fixed time stepILateSystem - system that executes in LateUpdate, after all Updates. Useful for logic that should run after main updatesICleanupSystem - system that executes after ILateSystem. Designed for cleanup operations, resetting states, and handling end-of-frame tasksBeware that ScriptableObject-based systems do still exist in 2024 version, but they are deprecated and will be removed in the future.
The type that contains the systems. Consider them as a "feature" to group the systems by their common purpose.
…A type that contains entities, components stashes, systems and root filter.
…A type that allows filtering entities constrained by conditions With and/or Without.
You can chain them in any order and quantity.
Call Build() to finalize the filter for further use.
var filter = this.World.Filter.With()
.With()
.Without()
.Build();
var firstEntityOrException = filter.First();
var firstEntityOrNull = filter.FirstOrDefault();
bool filterIsEmpty = filter.IsEmpty();
bool filterIsNotEmpty = filter.IsNotEmpty();
int filterLengthCalculatedOnCall = filter.GetLengthSlow();
A type that stores components data.
…Morpeh has providers for integration with Unity game engine.
This is a MonoBehaviour that allows you to create associations between GameObject and Entity.
For each ECS component, you can create a provider; it will allow you to change the component values directly through the inspector, use prefabs and use the workflow as close as possible to classic Unity development.
There are two main types of providers.
[!NOTE]
Precisely because providers allow you to work with component values directly from the kernel, because components are not stored in the provider, it only renders them;
We use third-party solutions for rendering inspectors like Tri Inspector or Odin Inspector.
It's a difficult task to render the completely different data that you can put into a component.
All providers do their work in the OnEnable() and OnDisable() methods.
This allows you to emulate turning components on and off, although the kernel does not have such a feature.
All providers are synchronized with each other, so if you attach several providers to one GameObject, they will be associated with one entity, and will not create several different ones.
Providers can be inherited and logic can be overridden in the Initialize() and Deinitialize() methods.
We do not use methods like Awake(), Start() and others, because the provider needs to control the creation of the entity and synchronize with other providers.
At the time of calling Initialize(), the entity is definitely created.
API:
var entityProvider = someGameObject.GetComponent();
var entity = entityProvider.Entity;var monoProvider = someGameObject.GetComponent();
var entity = monoProvider.Entity;
//returns serialized data or direct value of component
ref var data = ref monoProvider.GetData();
ref var data = ref monoProvider.GetData(out bool existOnEntity);
ref var serializedData = ref monoProvider.GetSerializedData();
var stash = monoProvider.Stash;We also have one additional provider that allows you to destroy an entity when a GameObject is removed from the scene.
You can simply hang it on a GameObject and no matter how many components are left on the entity, it will be deleted.
The provider is called RemoveEntityOnDestroy.
[!IMPORTANT]
All GIFs are hidden under spoilers. Press ➤ to open it.
First step: install Tri Inspector.
Second step: install Morpeh.
After installation import ScriptTemplates and Restart Unity. Let's create our first component and open it.
Right click in project window and select Create/ECS/Component. After it, you will see something like this.
using Scellecs.Morpeh;
using UnityEngine;
using Unity.IL2CPP.CompilerServices;
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
[System.Serializable]
public struct HealthComponent : IComponent {
}[!NOTE]
Don't care about attributes.
Il2CppSetOption attribute can give you better performance.
It is important to understand that this disables any checks for null, so in the release build any calls to a null object will lead to a hard crash.
We recommend that in places where you are in doubt about using this attribute, you check everything for null yourself.
Add health points field to the component.
public struct HealthComponent : IComponent {
public int healthPoints;
}It is okay.
Now let's create our first system.
Create a new C# class somewhere in your project and give it a name.
[!NOTE] You can also create IFixedSystem, ILateSystem and ICleanupSystem.
They are similar to MonoBehaviour's Update, FixedUpdate, LateUpdate. ICleanupSystem is called after all ILateSystem.
A system looks like this:
using Scellecs.Morpeh;
using UnityEngine;
using Unity.IL2CPP.CompilerServices;
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public sealed class HealthSystem : ISystem {
public World World { get; set; }
public void OnAwake() {
}
public void OnUpdate(float deltaTime) {
}
public void Dispose() {
}
}We have to add a filter to find all the entities with HealthComponent.
public sealed class HealthSystem : ISystem {
private Filter filter;
public World World { get; set; }
public void OnAwake() {
this.filter = this.World.Filter.With().Build();
}
public void OnUpdate(float deltaTime) {
}
public void Dispose() {
}
}[!NOTE]
You can chain filters by usingWith<>andWithout<>in any order.
For examplethis.World.Filter.With().With().Without().Build();
[!IMPORTANT]
Components are structs and if you want to change their values, then you must useref. It is recommended to always userefunless you specifically need a copy of the component.
Now we can iterate over our entities.
public sealed class HealthSystem : ISystem {
public World World { get; set; }
private Filter filter;
private Stash heNo open issues yet, or sync has not completed.