单例模式 (不继承MonoBehaviour)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Sington
{
public class SingleTonTest
{
//不继承mono的单例 常用于数据的管理类
public string name = "小明";
//存储 当前类唯一实例的对象
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();
}
}
}
继承 MonoBehaviour
//在游戏中 负责统筹管理的类 需要调到mono中的方法 Load<Sprite>
public int playerGold=100;
private static SingleTonMono instance;
public static SingleTonMono Instance
{
get {
return instance;
}
}
void Awake()
{
instance = this;
}
//this 代指当前类的对象,即脚本挂载的 GameObject