unity 游戏例模式

来源:互联网 发布:快速除法的算法实现 编辑:程序博客网 时间:2024/05/29 12:19

在unity 中经常会用到单例模式但是有时候单例模式使用了还是会自己创建对象,每次都会生成不同的对象,单例模式一般都是这样写的

public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T> ();
if (_instance == null)
{
Attackobj = new Attack();
//obj.hideFlags = HideFlags.HideAndDontSave;

}
}
return _instance;
}
}


如果我们将这个脚本继承了MonoBehaviour但是没有把他挂在场景中,此时就会不停的去创建该对象,如果你把它挂在场景中 则不会出现这样的问题,此时可以不继承MonoBehaviour,然后采用普通的C#单例模式进行对象的管理就可以了,也就是:

public static T Instance
{
get
{

if (_instance == null)
{
Attack obj = new Attack ();
//obj.hideFlags = HideFlags.HideAndDontSave;
_
}

return _instance;
}
}


这种方式就是C#的单例模式,

还有一张方式就是采用判断gameObject然后将这个脚本添加进入场景中进行调用也是可以使用

public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T> ();
if (_instance == null)
{
GameObject obj = new GameObject ();
//obj.hideFlags = HideFlags.HideAndDontSave;
_instance = obj.AddComponent<T> ();
}
}
return _instance;
}
}


这种现实模式就是如果没有,就在场景中创建一个Gameobject对象然后将这个脚本绑定到该对象上去,我今天遇到的就是我没有创建这个gameObject场景,此处记录一下


0 0
原创粉丝点击