单例模式

单例模式 (不继承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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值