BuildContext.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace YooAsset.Editor
  5. {
  6. public class BuildContext
  7. {
  8. private readonly Dictionary<System.Type, IContextObject> _contextObjects = new Dictionary<System.Type, IContextObject>();
  9. /// <summary>
  10. /// 清空所有情景对象
  11. /// </summary>
  12. public void ClearAllContext()
  13. {
  14. _contextObjects.Clear();
  15. }
  16. /// <summary>
  17. /// 设置情景对象
  18. /// </summary>
  19. public void SetContextObject(IContextObject contextObject)
  20. {
  21. if (contextObject == null)
  22. throw new ArgumentNullException("contextObject");
  23. var type = contextObject.GetType();
  24. if (_contextObjects.ContainsKey(type))
  25. throw new Exception($"Context object {type} is already existed.");
  26. _contextObjects.Add(type, contextObject);
  27. }
  28. /// <summary>
  29. /// 获取情景对象
  30. /// </summary>
  31. public T GetContextObject<T>() where T : IContextObject
  32. {
  33. var type = typeof(T);
  34. if (_contextObjects.TryGetValue(type, out IContextObject contextObject))
  35. {
  36. return (T)contextObject;
  37. }
  38. else
  39. {
  40. throw new Exception($"Not found context object : {type}");
  41. }
  42. }
  43. }
  44. }