GameObjectManager.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MongoDB.Bson;
  5. namespace Component
  6. {
  7. public class GameObjectManager
  8. {
  9. private readonly Dictionary<ObjectId, GameObject> gameObjects =
  10. new Dictionary<ObjectId, GameObject>();
  11. private readonly Dictionary<int, Dictionary<ObjectId, GameObject>> typeGameObjects =
  12. new Dictionary<int, Dictionary<ObjectId, GameObject>>();
  13. public void Add(GameObject gameObject)
  14. {
  15. this.gameObjects.Add(gameObject.Id, gameObject);
  16. if (!this.typeGameObjects.ContainsKey(gameObject.Type))
  17. {
  18. this.typeGameObjects.Add(gameObject.Type, new Dictionary<ObjectId, GameObject>());
  19. }
  20. this.typeGameObjects[gameObject.Type].Add(gameObject.Id, gameObject);
  21. }
  22. public GameObject Get(ObjectId id)
  23. {
  24. GameObject gameObject = null;
  25. this.gameObjects.TryGetValue(id, out gameObject);
  26. return gameObject;
  27. }
  28. public GameObject[] GetOneType(int type)
  29. {
  30. Dictionary<ObjectId, GameObject> oneTypeGameObjects = null;
  31. if (!this.typeGameObjects.TryGetValue(type, out oneTypeGameObjects))
  32. {
  33. return new GameObject[0];
  34. }
  35. return oneTypeGameObjects.Values.ToArray();
  36. }
  37. public bool Remove(GameObject gameObject)
  38. {
  39. if (gameObject == null)
  40. {
  41. throw new ArgumentNullException("gameObject");
  42. }
  43. if (!this.gameObjects.Remove(gameObject.Id))
  44. {
  45. return false;
  46. }
  47. if (!this.typeGameObjects[gameObject.Type].Remove(gameObject.Id))
  48. {
  49. return false;
  50. }
  51. return true;
  52. }
  53. public bool Remove(ObjectId id)
  54. {
  55. GameObject gameObject = this.Get(id);
  56. if (gameObject == null)
  57. {
  58. return false;
  59. }
  60. return this.Remove(gameObject);
  61. }
  62. }
  63. }