PrefabManager.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UniFramework.Pooling;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using YooAsset;
  5. namespace GFGGame
  6. {
  7. public class PrefabManager : SingletonBase<PrefabManager>
  8. {
  9. private Spawner _entitySpawner;
  10. private Dictionary<string, bool> poolCreated = new Dictionary<string, bool>();
  11. public void Init()
  12. {
  13. // 创建游戏对象发生器
  14. _entitySpawner = UniPooling.CreateSpawner(VersionController.DefaultPackage);
  15. }
  16. public GameObject SpawnSync(string resPath)
  17. {
  18. this.poolCreated.TryGetValue(resPath, out bool poolCreated);
  19. if (!poolCreated)
  20. {
  21. // 创建游戏对象池,销毁时间单位为秒
  22. _entitySpawner.CreateGameObjectPoolAsync(resPath, false, 0, 1, 60);
  23. }
  24. var handle = _entitySpawner.SpawnSync(resPath);
  25. var assetReleaser = handle.GameObj.GetComponent<AssetReleaser>();
  26. if (assetReleaser == null)
  27. {
  28. assetReleaser = handle.GameObj.AddComponent<AssetReleaser>();
  29. }
  30. assetReleaser.SetSpawn(resPath, handle);
  31. return handle.GameObj;
  32. }
  33. public GameObject InstantiateSync(string resPath)
  34. {
  35. AssetOperationHandle handle = YooAssets.LoadAssetSync<GameObject>(resPath);
  36. GameObject gameObject = handle.InstantiateSync();
  37. AssetReleaser assetReleaser = gameObject.AddComponent<AssetReleaser>();
  38. assetReleaser.SetRes(resPath, handle);
  39. return gameObject;
  40. }
  41. public void Restore(GameObject gameObject)
  42. {
  43. if (gameObject == null)
  44. {
  45. return;
  46. }
  47. AssetReleaser assetRestorer = gameObject.GetComponent<AssetReleaser>();
  48. if (assetRestorer != null && assetRestorer.IsSpawn)
  49. {
  50. assetRestorer.Restore();
  51. }
  52. else
  53. {
  54. GameObject.DestroyImmediate(gameObject);
  55. }
  56. }
  57. }
  58. }