单例-接口模式
使用接口方式实现的单例可以继承其它类,更加方便

using System.Collections;
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
namespace ZYF
{
public interface ISingleton<TMono> where TMono : MonoBehaviour
{
private static string rootName = "MonoSingletonRoot";
private static GameObject monoSingletionRoot;
private static bool isSpawnRootGo = false;
static TMono _instance;
public static TMono Instance
{
get {
if (_instance == null && Application.isPlaying)
{
_instance = GameObject.FindObjectOfType<TMono>();
if (_instance == null)
{
if (monoSingletionRoot == null)
{
monoSingletionRoot = GameObject.Find(rootName);
if (monoSingletionRoot == null && isSpawnRootGo ==false) {
isSpawnRootGo=true;
monoSingletionRoot = new GameObject(rootName);
monoSingletionRoot.OnDestroyAsObservable().Subscribe(_ => {
isSpawnRootGo = false;
}).AddTo(monoSingletionRoot);
}
}
if (monoSingletionRoot != null)
{
_instance = monoSingletionRoot.GetComponent<TMono>();
}
if (_instance == null)
{
if (monoSingletionRoot != null)
{
_instance = monoSingletionRoot.AddComponent<TMono>();
}
else
{
Debug.Log(rootName + "null!!!");
}
}
}
}
if (_instance == null)
{
Debug.Log(typeof(TMono).Name + "Null");
}
return _instance;
}
}
}
}
- 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