Browse Source

修复游戏结束还会刷怪的问题

WGL 4 tháng trước cách đây
mục cha
commit
206d5bd006
1 tập tin đã thay đổi với 8 bổ sung28 xóa
  1. 8 28
      ActionTowerDefense/Assets/Scripts/EnemyCreater.cs

+ 8 - 28
ActionTowerDefense/Assets/Scripts/EnemyCreater.cs

@@ -141,20 +141,6 @@ public class EnemyCreater : MonoBehaviour
         //    }
         //}
     }
-    void OnDestroy()
-    {
-        // 当 GameObject 销毁(如游戏停止)时取消任务
-        StopAllCoroutines();
-        _cancellationTokenSource?.Cancel();
-        _cancellationTokenSource?.Dispose();
-    }
-
-    void OnDisable()
-    {
-        StopAllCoroutines();
-        _cancellationTokenSource?.Cancel();
-        _cancellationTokenSource?.Dispose();
-    }
     public void OnGameTimeChange(float gameTime)
     {
         for (int i = idRange[0] + 1; i <= idRange[1]; i++)
@@ -229,15 +215,12 @@ public class EnemyCreater : MonoBehaviour
                 Vector3 pos = new Vector3(cfgCreateEnemy.Position[j], cfgCreateEnemy.Position[j + 1], 0);
                 CreateEnemy(cfgCreateEnemy, pos, true);
             }
-            try
+            await Task.Delay((int)(TimeInterval * 1000), _cancellationTokenSource.Token);
+            if (this == null || !this.isActiveAndEnabled)
             {
-                await Task.Delay((int)(TimeInterval * 1000), _cancellationTokenSource.Token);
+                Debug.Log("取消任务");
+                return; // 如果对象已被销毁,直接返回
             }
-            catch (TaskCanceledException)
-            {
-                return;
-            }
-
         }
         List<int> randomPos = new(cfgCreateEnemy.Position);
         for (int i = 0; i < num2; i++)
@@ -276,15 +259,12 @@ public class EnemyCreater : MonoBehaviour
                 Vector3 pos = new Vector3(cfgCreateEnemy.Position[j], cfgCreateEnemy.Position[j + 1], 0);
                 CreateEnemy(cfgCreateEnemy, pos, true);
             }
-            try
+            await Task.Delay((int)(TimeInterval * 1000), _cancellationTokenSource.Token);
+            if (this == null || !this.isActiveAndEnabled)
             {
-                await Task.Delay((int)(TimeInterval * 1000), _cancellationTokenSource.Token);
+                Debug.Log("取消任务");
+                return; // 如果对象已被销毁,直接返回
             }
-            catch (TaskCanceledException)
-            {
-                return;
-            }
-
         }
         List<int> randomPos = new(cfgCreateEnemy.Position);
         for (int i = 0; i < num2; i++)