多线程单例使用说明

 单例脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    private static NewBehaviourScript instance;
    private static readonly object locker = new object();
    /*通过此单例模式,在外部脚本可以获取下方 cube,
     不过cube为object=null的类型存在,即使在Hierarchy上托拽对象也获取不到实例*/
    public GameObject cube;
    //通过此单例模式,在外部脚本,此种字段可以获取并更改str
    public string str;
    //在外部脚本,通过单例无法获取 公开静态字段number
    public static int number;
    private NewBehaviourScript()
    {

    }
    public static NewBehaviourScript Get_instance()
    {
        if (instance == null)
        {
            lock (locker)
            {
                if (instance == null)
                {
                    instance = new NewBehaviourScript();
                }
            }
        }  
        return instance;
    }
   
}

调用脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ceshi : MonoBehaviour {
    public GameObject obj;
	// Use this for initialization
	void Start () {
        //获取实例
        NewBehaviourScript instance = NewBehaviourScript.Get_instance();
        //直接更改
        instance.str = "fanhongyun";
        /*必须赋予实例  因此,在涉及到大量对象时可以考虑在单例中建造list或Dictionary,
         在资源脚本中将实例对象加载进单例对应的集合或字典中*/
        instance.cube = transform.gameObject;
        instance.cube.transform.position = new Vector3(10, 10, 10);

    }
	
	// Update is called once per frame
	void Update () {
		
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值