-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAutoDisposeSelf.cs
More file actions
69 lines (60 loc) · 2 KB
/
AutoDisposeSelf.cs
File metadata and controls
69 lines (60 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Collections;
using UnityEngine;
namespace GameUtil
{
[DisallowMultipleComponent]
public class AutoDisposeSelf : MonoBehaviour, ISpawnHandler, IDisposeHandler
{
public float Delay = 1;
public bool IgnoreTimeScale;
private Coroutine mCoroutine;
private void Start()
{
DelayDisposeSelf();
}
private void OnDestroy()
{
StopDelayDisposeSelf();
}
public void OnSpawn()
{
DelayDisposeSelf();
}
public void OnDispose()
{
StopDelayDisposeSelf();
//这里还需要再次销毁一下
//因为可能是嵌套的外部对象Dispose了,导致自己响应到OnDispose
//所以还需要再销毁一次确保自身被Dispose
//重复调用DisposeGameObject不会有错误行为
ObjectPool.Instance.DisposeGameObject(gameObject);
}
private void StopDelayDisposeSelf()
{
//使用ObjectPool.Instance开启/关闭协程,避免因为自身隐藏导致协程停止
if (mCoroutine != null)
ObjectPool.SafeStopCoroutine(mCoroutine);
mCoroutine = null;
}
private void DelayDisposeSelf()
{
if (mCoroutine != null) return;
if (Delay <= 0)
{
ObjectPool.Instance.DisposeGameObject(gameObject);
return;
}
//使用ObjectPool.Instance开启/关闭协程,避免因为自身隐藏导致协程停止
mCoroutine = ObjectPool.SafeStartCoroutine(DelayDisposeSelfInternal());
}
IEnumerator DelayDisposeSelfInternal()
{
if (IgnoreTimeScale)
yield return new WaitForSecondsRealtime(Delay);
else
yield return new WaitForSeconds(Delay);
mCoroutine = null;
ObjectPool.Instance.DisposeGameObject(gameObject);
}
}
}