unity学习——单例模式

来源:互联网 发布:服装设计师 知乎 编辑:程序博客网 时间:2024/06/07 09:29

顾名思义单例模式表达的是只能创建一个实例。通常用在需要统一管理某项实物的时候用到。单例模式我们是通过将构造函数设为私有来实现。

  using System.Collections;using System.Collections.Generic;using UnityEngine;public class SounderManager {//不能继承MonoBehaviour    private static SounderManager instance;//设置一个私有的静态的SounderManager对象    private SounderManager()//设置私有构造方法    {    }    public static SounderManager GetInstance()//使用公共静态方法获取唯一的实例    {    //如果实例为null说明首次创建,如果不是首次创建,我们直接返回我们之前创建的SoundManager实例instance        if (instance == null)            instance = new SounderManager();        return instance;    }    public void Play()    {        Debug.Log("Play");    }}

当我们在其他类中直接new SoundManager时,vs会直接报错
这里写图片描述
所以我们不能通过new来 创建对象!!!

using System.Collections;using System.Collections.Generic;using UnityEngine;public class SoundMangagerText : MonoBehaviour {    // Use this for initialization    void Start () {        SounderManager sm = SounderManager.GetInstance();        sm.Play();    }    // Update is called once per frame    void Update () {    }}

我们需要通过公共的静态方法GetInstance来实现。

原创粉丝点击