Pool.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Artemis;
  6. using System.Reflection;
  7. namespace StarWarrior
  8. {
  9. public class GamePool : ArtemisPool
  10. {
  11. Dictionary<Type, Bag<Component>> componentPool = new Dictionary<Type, Bag<Component>>();
  12. int limit = 0;
  13. Type[] components;
  14. public GamePool(int limit, Type[] components)
  15. {
  16. this.limit = limit;
  17. this.components = components;
  18. }
  19. public void Initialize()
  20. {
  21. foreach (Type type in components)
  22. {
  23. MethodInfo methodInfo = GetType().GetMethod("AddComponentType");
  24. MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(new Type[] { type });
  25. genericMethodInfo.Invoke(this, null);
  26. }
  27. Populate(limit);
  28. }
  29. public void Populate(int quantity)
  30. {
  31. for (int i = 0; i < quantity; i++)
  32. {
  33. foreach (Type type in components)
  34. {
  35. AddComponent(type, (Component)Activator.CreateInstance(type));
  36. }
  37. }
  38. }
  39. public void AddComponentType<T>() where T : Component
  40. {
  41. Bag<Component> bag = new Bag<Component>();
  42. componentPool.Add(typeof(T), bag);
  43. }
  44. public void AddComponent(Type type, Component c)
  45. {
  46. Bag<Component> bag;
  47. if (componentPool.TryGetValue(type, out bag))
  48. {
  49. bag.Add(c);
  50. }
  51. }
  52. public Component TakeComponent<T>() where T : Component
  53. {
  54. Bag<Component> bag;
  55. if (componentPool.TryGetValue(typeof(T), out bag))
  56. {
  57. Component c = bag.RemoveLast();
  58. if (c == null)
  59. {
  60. Populate((int)(limit * 0.25));
  61. c = bag.RemoveLast();
  62. }
  63. return c;
  64. }
  65. else
  66. {
  67. return null;
  68. }
  69. }
  70. }
  71. }