我常用的Unity单例模式

在开发中,想必用到的最多的就是单例模式了。那么今天就分享一下我经常在开发中用到的单例模式。

伪单例

首先 我们的脚本要继承MonoBehaviour
这种单例的使用中,脚本必须挂在对象上面,当我们调用的时候,就可以直接调用SingleScript类里面的变量和方法了。

1
2
3
4
5
6
7
8
9
10
11
12
using UnityEngine;

public class SingleScript : MonoBehaviour
{

public static SingleScript Instance;

private void Awake()
{
Instance = this;
}
}

不继承MonoBehaviour的单例

1
2
3
4
5
6
7
8
9
10
11
12
13
public class SingleScriptClass
{
public int game = 0;

private static SingleScriptClass _instance;

public static SingleScriptClass Instance()
{
if (null == _instance)
_instance = new SingleScriptClass();
return _instance;
}
}

这样每次调用时候Instance后面必须加一对括号,很难受,那么还有一种办法,就是使用属性了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SingleScriptClass
{
public int game = 0;

private static SingleScriptClass _instance;

public static SingleScriptClass Instance
{
get
{
if (null == _instance)
{
_instance = new SingleScriptClass();
}
return _instance;
}
}
}

那么怎么调用?直接跨脚本调用,像下面这样。

1
2
3
4
5
6
7
8
9
10
11
12
using UnityEngine;

public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int game = SingleScript.Instance.game;
//int game2 = SingleScriptClass.Instance().game;
int game3 = SingleScriptClass.Instance.game;
}
}

不需要重复实现的单例

常用的单例的使用就是这样了,但是这样写还是有一些麻烦的,因为每次实现单例,都需要在每个类中实现一遍单例很麻烦。那么为了解决这个问题,下面的这种单例模式出现了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class SingleMode<T> where T : class , new()  //限制继承自单例类的类型,必须是类,必须new()
{
private static T instance;

public static T Instance
{
get
{
if (null == instance)
{
instance = new T();
}

return instance;
}
}
}
public class TestSingle : SingleMode<TestSingle>
{
public int game = 0;
}

这样的话,在实现新的单例的时候,只需要继承自单例类,就可以不用再写一遍单例的实现了,调用方法还是老样子,像下面这样。

1
2
3
4
5
6
7
8
9
10
using UnityEngine;

public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int game4 = TestSingle.Instance.game;
}
}

好了,今天的分享就到这,我们下期见。
如果有什么问题或者有什么建议,欢迎在文章下方留言或者进Unityの大学技术交流群一起探讨。