Skip to content

Instantly share code, notes, and snippets.

@funrep
Created December 14, 2015 15:02
Show Gist options
  • Select an option

  • Save funrep/95cfa3e4ef5565b3402e to your computer and use it in GitHub Desktop.

Select an option

Save funrep/95cfa3e4ef5565b3402e to your computer and use it in GitHub Desktop.
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
Copy link
Copy Markdown

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