单例模式分为两种一种是继承mono的一种是不继承mono的
不继承mono的 常用于数据的管理
不继承mono:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Sington
{
public class SingleTonTest /*: MonoBehaviour */
{
//不继承mono的单利 常用于数据的管理类
public string name = "VR-1";
//存储 当前类唯一实例的对象
private static SingleTonTest instance;
//需要一个位置对当前对象进行实例化 而且是唯一的实例化
//public static SingleTonTest GetInstance()
//{
// if (instance == null)
// {
// //当前类没有实例化
// instance = new SingleTonTest();
// }
// return instance;
//}
//属性访问器形式
public static SingleTonTest Instance
{
get {
if (instance == null)
{
instance = new SingleTonTest();
}
return instance;
}
}
public void Print()
{
System.Console.WriteLine("打印方法");
}
/// <summary>
/// 当前需要单例的类的构造私有化
/// </summary>
private SingleTonTest()
{
}
}
public class Test
{
public void Main()
{
//1.方法形式获取单例
//SingleTonTest.GetInstance();
//2.属性访问器形式获取单例
SingleTonTest a = SingleTonTest.Instance;
string name = a.name;
a.Print();
}
}
}
继承mono的
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleTonMono : MonoBehaviour {
//继承mono的单利
//在游戏中 负责统筹管理的类 需要调到mono中的方法 Load<Sprite>
public int playerGold=100;
private static SingleTonMono instance; //静态的可以用类去调用
//比如在别脚本中用 singleton.ins 来调用下面写的方法Instance
public static SingleTonMono Instance
{
get {
return instance;
}
}
void Awake()
{
instance = this;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}