Created
August 11, 2012 15:07
-
-
Save TinkerWorX/3325154 to your computer and use it in GitHub Desktop.
My take on an entity system framework in C#.
This file contains 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; | |
using System.Collections.Generic; | |
namespace TinkerWorX.EntitySystemFramework | |
{ | |
public sealed class Entity | |
{ | |
private readonly Dictionary<Type, IComponent> components = new Dictionary<Type, IComponent>(); | |
public void Add(IComponent component) | |
{ | |
if (component == null) throw new ArgumentNullException("component"); | |
this.components.Add(component.GetType(), component); | |
} | |
public void Add(IEnumerable<IComponent> components) | |
{ | |
if (components == null) throw new ArgumentNullException("components"); | |
foreach (var component in components) | |
{ | |
this.Add(component); | |
} | |
} | |
public void Add(params IComponent[] components) | |
{ | |
if (components == null) throw new ArgumentNullException("components"); | |
foreach (var component in components) | |
{ | |
this.Add(component); | |
} | |
} | |
public T Get<T>() where T : IComponent | |
{ | |
return (T)this.components[typeof(T)]; | |
} | |
public void Remove<T>() where T : IComponent | |
{ | |
this.components.Remove(typeof(T)); | |
} | |
public Boolean TryAdd(IComponent component) | |
{ | |
if (this.components.ContainsKey(component.GetType())) | |
return false; | |
this.components.Add(component.GetType(), component); | |
return true; | |
} | |
public Boolean TryGet<T>(out T component) where T : IComponent | |
{ | |
IComponent componentBase; | |
var result = this.components.TryGetValue(typeof(T), out componentBase); | |
component = (T)componentBase; | |
return result; | |
} | |
public Boolean TryRemove<T>(out T component) where T : IComponent | |
{ | |
IComponent componentBase; | |
var result = this.components.TryGetValue(typeof(T), out componentBase); | |
this.components.Remove(typeof(T)); | |
component = (T)componentBase; | |
return result; | |
} | |
public Boolean TryRemoveAll(out IEnumerable<IComponent> components) | |
{ | |
components = new HashSet<IComponent>(this.components.Values); | |
this.components.Clear(); | |
return true; | |
} | |
} | |
public interface IComponent | |
{ | |
void Reset(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment