Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / manager / ResourceManager.cs
  1. using System.Collections.Generic;
  2. using Godot;
  3.  
  4. /// <summary>
  5. /// 资源管理器
  6. /// </summary>
  7. public static class ResourceManager
  8. {
  9. /// <summary>
  10. /// 颜色混合材质
  11. /// </summary>
  12. public static ShaderMaterial BlendMaterial
  13. {
  14. get
  15. {
  16. if (_shadowMaterial == null)
  17. {
  18. _shadowMaterial = ResourceLoader.Load<ShaderMaterial>(ResourcePath.resource_materlal_Blend_tres);
  19. }
  20.  
  21. return _shadowMaterial;
  22. }
  23. }
  24.  
  25. private static ShaderMaterial _shadowMaterial;
  26.  
  27. /// <summary>
  28. /// 颜色混合Shader
  29. /// </summary>
  30. public static Shader BlendShader
  31. {
  32. get
  33. {
  34. if (_shadowShader == null)
  35. {
  36. _shadowShader = ResourceLoader.Load<Shader>(ResourcePath.resource_materlal_Blend_gdshader);
  37. }
  38.  
  39. return _shadowShader;
  40. }
  41. }
  42.  
  43. private static Shader _shadowShader;
  44.  
  45. private static readonly Dictionary<string, object> CachePack = new Dictionary<string, object>();
  46.  
  47. /// <summary>
  48. /// 加载资源对象, 并且缓存当前资源对象, 可频繁获取
  49. /// </summary>
  50. /// <param name="path">资源路径</param>
  51. /// <param name="useCache">是否使用缓存中的资源</param>
  52. public static T Load<T>(string path, bool useCache = true) where T : class
  53. {
  54. if (!useCache)
  55. {
  56. var res = ResourceLoader.Load<T>(path, null, ResourceLoader.CacheMode.Ignore);
  57. if (res == null)
  58. {
  59. GD.PrintErr("加载资源失败, 未找到资源: " + path);
  60. return default;
  61. }
  62.  
  63. return res;
  64. }
  65.  
  66. if (CachePack.TryGetValue(path, out var pack))
  67. {
  68. return pack as T;
  69. }
  70.  
  71. pack = ResourceLoader.Load<T>(path);
  72. if (pack != null)
  73. {
  74. CachePack.Add(path, pack);
  75. return pack as T;
  76. }
  77. else
  78. {
  79. GD.PrintErr("加载资源失败, 未找到资源: " + path);
  80. }
  81.  
  82. return default;
  83. }
  84.  
  85. /// <summary>
  86. /// 加载并且实例化场景, 并返回
  87. /// </summary>
  88. /// <param name="path">场景路径</param>
  89. public static T LoadAndInstantiate<T>(string path) where T : Node
  90. {
  91. var packedScene = Load<PackedScene>(path);
  92. return packedScene.Instantiate<T>();
  93. }
  94. }