Skip to content

Instantly share code, notes, and snippets.

@funrep funrep/ECS.cs
Created Dec 14, 2015

Embed
What would you like to do?
Barebones Entity Component System in C#
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);
}
}
@joleeee

This comment has been minimized.

Copy link

joleeee commented Jul 26, 2018

Thanks for posting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.