最近在做切换场景的一款游戏时遇到了一个问题,场景和场景之间我需要相互传递并处理数据,于是就想到了单例,单例模式的共同优点就是只实例一次,节省内存。今天我想以个人理解总结一下单例模式。我一共列举了三种模式:
一、我在unity里面添加了一个物体,添加脚本来测试三个模式,测试脚本如下:
public class Test : MonoBehaviour
{
void Update()
{
if(Input.GetMouseButtonDown(0))
{
//TestC.Instance.MyTest();//C#模式
//TestUnity.Instance.MyTest();//unity模式
//TestGeo.Instance.MyTest();//单个物体单脚本模式··脚本在场景的摄像机上
}
if (Input.GetMouseButtonDown(1))
{//切换场景,方便再次查看数据
SceneManager.LoadScene(
SceneManager.GetActiveScene().buildIndex.Equals(0) ? 1 : 0);
}
}
}
二、下面主要介绍三个模式主要代码写法及解释
1、利用C#形式的单例模式:
这个模式切换场景num的值都会增加不会重新计数(废话不说,直接看代码)
public class TestC
{
private int num = 0;
private static TestC _instance;
public static TestC Instance
{
get
{
Debug.Log("是否实例");
if (_instance==null)
{
Debug.Log("实例化C#");
_instance = new TestC();
}
return _instance;
}
}
public void MyTest()
{
int temp = num++;
Debug.Log("测试单例num="+ temp);
}
}
2、利用unity形式的单例模式:
这个模式切换场景num的值都会增加不会重新计数(废话不说,直接看代码)
public class TestUnity : MonoBehaviour
{
private int num = 0;
private static TestUnity _instance;
public static TestUnity Instance
{
get
{
Debug.Log("是否实例");
if (_instance == null)
{
Debug.Log("实例化Unity");
GameObject Geo = new GameObject("NumData");
_instance = Geo.AddComponent<TestUnity>();
DontDestroyOnLoad(Geo);//切换场景不销毁··切换场景不丢数据的关键语句
}
return _instance;
}
}
public void MyTest()
{
int temp = num++;
Debug.Log("测试单例num=" + temp);
}
}
2、利用单个物体单脚本的单例模式:
这个模式只适用于一个场景,并且场景中只有一个物体挂载该脚本,优点其一在于方便访问(废话不说,直接看代码)
public class TestGeo : MonoBehaviour
{
private int num = 0;
public static TestGeo Instance;
private void Awake()
{
Debug.Log("实例化Geo");
Instance = this;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("加一");
num++;
}
}
public void MyTest()
{
Debug.Log("测试单例num=" + num);
}
}
最后将我写的一个demo分享给大家,让大家更容易理解,如果有更深入的理解,欢迎各位打扰
demo地址:https://download.csdn.net/download/cgexplorer/10879309