DelayDestory.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. namespace WXB
  4. {
  5. public class DelayDestory : MonoBehaviour
  6. {
  7. static List<GameObject> Destorys = new List<GameObject>();
  8. static List<GameObject> DestroyImmediates = new List<GameObject>();
  9. #if UNITY_EDITOR
  10. static DelayDestory()
  11. {
  12. UnityEditor.EditorApplication.update += UpdateEditor;
  13. }
  14. static void UpdateEditor()
  15. {
  16. if (!Application.isPlaying)
  17. {
  18. OnUpdate();
  19. }
  20. }
  21. #endif
  22. static DelayDestory instance = null;
  23. static void Init()
  24. {
  25. #if UNITY_EDITOR
  26. if (!Application.isPlaying)
  27. return;
  28. #endif
  29. if (instance == null)
  30. {
  31. instance = (new GameObject("DelayDestory")).AddComponent<DelayDestory>();
  32. //instance.gameObject.hideFlags = HideFlags.HideAndDontSave;
  33. }
  34. }
  35. public static void Destroy(GameObject go)
  36. {
  37. Init();
  38. Destorys.Add(go);
  39. }
  40. public static void DestroyImmediate(GameObject go)
  41. {
  42. Init();
  43. DestroyImmediates.Add(go);
  44. }
  45. void LateUpdate()
  46. {
  47. #if UNITY_EDITOR
  48. if (!Application.isPlaying)
  49. return;
  50. #endif
  51. OnUpdate();
  52. }
  53. static void OnUpdate()
  54. {
  55. for (int i = 0; i < Destorys.Count; ++i)
  56. {
  57. if (Destorys[i] != null)
  58. {
  59. Object.Destroy(Destorys[i]);
  60. }
  61. }
  62. Destorys.Clear();
  63. for (int i = 0; i < DestroyImmediates.Count; ++i)
  64. {
  65. if (DestroyImmediates[i] != null)
  66. {
  67. Object.DestroyImmediate(DestroyImmediates[i]);
  68. }
  69. }
  70. DestroyImmediates.Clear();
  71. }
  72. }
  73. }