Skip to content

Instantly share code, notes, and snippets.

@copygirl
Created December 1, 2014 21:17
Show Gist options
  • Save copygirl/907a445c5a8579b8b0b4 to your computer and use it in GitHub Desktop.
Save copygirl/907a445c5a8579b8b0b4 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace ScriptingTestingGrounds
{
public class ComponentCollection : ICollection<IGameComponent>
{
private IDictionary<Type, IGameComponent> dict =
new Dictionary<Type, IGameComponent>();
public GameEntity Entity { get; private set; }
public int Count { get { dict.Count; } }
public bool IsReadOnly { get { return false; } }
public event Action<IGameComponent> OnAdded;
public event Action<IGameComponent> OnRemoved;
public ComponentCollection(GameEntity entity)
{
Entity = entity;
}
public T Get<T>()
{
T component = null;
dict.TryGetValue(typeof(T), out component);
return component;
}
#region ICollection implementation
public void Add(IGameComponent component)
{
dict.Add(component.GetType(), component);
if (OnAdded != null)
OnAdded(component);
}
public bool Remove(IGameComponent component)
{
if (dict.Remove(component.GetType())) {
if (OnRemoved != null)
OnRemoved(component);
return true;
} else return false;
}
public void Clear()
{
if (OnRemoved != null) {
IList<IGameComponent> list = new List<IGameComponent>(dict.Values);
dict.Clear();
foreach (IGameComponent component in list)
OnRemoved(component);
} else dict.Clear();
}
public bool Contains(IGameComponent component)
{
dict.ContainsKey(component.GetType());
}
public void CopyTo(IGameComponent[] array, int arrayIndex)
{
dict.Values.CopyTo(array, arrayIndex);
}
#endregion
#region IEnumerable implementation
public IEnumerator<IGameComponent> GetEnumerator()
{
return dict.Values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
using System;
using System.Collections.Generic;
namespace ScriptingTestingGrounds
{
public class GameEntity
{
public Guid ID { get; internal set; }
public ComponentCollection Components { get; private set; }
public GameEntity()
{
Components = new ComponentCollection(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment