单例脚本
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 () {
}
}