美文网首页Unity+Code Learning
【Unity】Singleton单例的简单运用

【Unity】Singleton单例的简单运用

作者: zitaoye | 来源:发表于2019-07-12 11:50 被阅读0次

    例如需要有一个LevelManger要在很多的脚本中被使用,并且其只有一个;
    并不是将整个class变成一个static,因为那样似乎整个类就不能有实例的部分了;

    可以通过在下面加入

    public class LevelManager : MonoBehaviour
    {
        //SINGLETON 单例
        public static LevelManager instance;
    
        void Awake()
        {     
            if (instance==null)
            {
                instance=this;
            }
        }
    }
    

    然后使用的时候采用

    LevelManager.instance. 
    
    

    静态方法同样可以,注意不要忘记加名字:

    public static void HAHAHAH(){
    }
    

    使用的时候用

    LevelManager.HAHAHAH();
    

    感谢@haoming大佬的莅临指导

    相关文章

      网友评论

        本文标题:【Unity】Singleton单例的简单运用

        本文链接:https://www.haomeiwen.com/subject/felekctx.html