ObjectCollector.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace XGame.Framework.ObjectCollection
  5. {
  6. [Serializable]
  7. public class ObjectCollector : IObjectCollector
  8. {
  9. #if UNITY_EDITOR
  10. public Type collectorType = typeof(GameObject);
  11. public Type[] blackTypes = null;
  12. /// <summary>
  13. /// 绑定的脚本类型,生成代码用
  14. /// </summary>
  15. [SerializeField]
  16. public List<string> bindTypes = new List<string>();
  17. #endif
  18. [SerializeField]
  19. public List<string> keys = new List<string>();
  20. [SerializeField]
  21. public List<UnityEngine.Object> values = new List<UnityEngine.Object>();
  22. private Dictionary<string, UnityEngine.Object> _objectsMap;
  23. private bool _isInited = false;
  24. public UnityEngine.Object this[string key]
  25. {
  26. get
  27. {
  28. if (!_isInited) CacheDict();
  29. if (_objectsMap.TryGetValue(key, out UnityEngine.Object value))
  30. return value;
  31. Log.Debug($"Can't find the key: {key}, Please Check it");
  32. return null;
  33. }
  34. }
  35. public List<string> Keys => keys;
  36. public List<UnityEngine.Object> Objects => values;
  37. public T GetComponent<T>(string key) where T : Component
  38. {
  39. var obj = this[key];
  40. if (obj is GameObject go)
  41. {
  42. return go.GetComponent<T>();
  43. }
  44. if (obj is Component component)
  45. {
  46. return component.gameObject.GetComponent<T>();
  47. }
  48. //Log.Debug($"Can't find Component. key: {key} Type:{typeof(T)}");
  49. return null;
  50. }
  51. public GameObject GetGameObject(string key)
  52. {
  53. var obj = this[key];
  54. if (obj is GameObject go)
  55. {
  56. return go;
  57. }
  58. if (obj is Component component)
  59. {
  60. return component.gameObject;
  61. }
  62. Log.Error($"Can't find GameObject. key: {key}");
  63. return null;
  64. }
  65. private void CacheDict()
  66. {
  67. _isInited = true;
  68. _objectsMap = new Dictionary<string, UnityEngine.Object>(keys.Count);
  69. for (int i = 0, length = keys.Count; i < length; i++)
  70. {
  71. _objectsMap[keys[i]] = values[i];
  72. }
  73. }
  74. }
  75. }