返回

单例模式

单例模式简介

单例模式是指让一个类在该程序集合中成为唯一实例,防止其他模块将该类重复实例化。 单例模式多用于程序集合中的管理类上,因为在功能集合中多个重复管理类会导致其冲突重复占用内存。 **注意:**如果想调用单例类,切记该类无法被new出来。且变量要增加state设置为全局变量。

简单代码例子

继承mono的写法,拖拽相当于new,直接拖拽挂载脚本

  • 单例模块
public class TeachSingle : MonoBehaviour
{
    public static TeachSingle instance;
    private void Awake()
    {
        instance = this;
    }
    public void TeachSingles()
    {
    }
}

非继承的写法

public class TeachSingle
{
    public static TeachSingle instance = null;
  get
     {
        if(instance ==null)
            instance  = new TeachSingle();
        return instance ;
     } 
    public void TeachSingles()
    {
    }
}
  • 在其他类中调用该类
 TeachSingle.instance.TeachSingles();
Licensed under CC BY-NC-SA 4.0
0