Created
December 14, 2015 15:02
-
-
Save funrep/95cfa3e4ef5565b3402e to your computer and use it in GitHub Desktop.
Barebones Entity Component System in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
namespace ProjectCC | |
{ | |
class World | |
{ | |
private List<Entity> Entities; | |
private List<System> Systems; | |
public World() | |
{ | |
this.Entities = new List<Entity>(); | |
this.Systems = new List<System>(); | |
} | |
public void AddSystem(System sys) | |
{ | |
this.Systems.Add(sys); | |
} | |
public void Step() | |
{ | |
List<Component> entComps, comps; | |
foreach (var ent in this.Entities) | |
{ | |
entComps = ent.Components; | |
foreach (var sys in this.Systems) | |
{ | |
comps = entComps.Where( | |
comp => sys.ComponentNames.Contains(comp.Name)).ToList(); | |
sys.Run(comps); | |
} | |
} | |
} | |
} | |
class Entity | |
{ | |
private int id; | |
public List<Component> Components { get; } | |
public Entity(List<Component> comps) | |
{ | |
this.id = IdGenerator.New(); | |
this.Components = comps; | |
} | |
public void AddComponent(Component comp) | |
{ | |
this.Components.Add(comp); | |
} | |
public void RemoveComponent(string name) | |
{ | |
foreach (var comp in this.Components) | |
{ | |
if (comp.Name == name) | |
{ | |
this.Components.Remove(comp); | |
} | |
} | |
} | |
} | |
abstract class Component | |
{ | |
// user-defined, contains data | |
abstract public string Name { get; } | |
} | |
abstract class System | |
{ | |
// user-defined, contains logic | |
abstract public List<string> ComponentNames { get; } | |
abstract public void Run(List<Component> comps); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for posting.