Unity3d中封装单例模式,Singleton
很多时候我们需要A脚本调用B脚本里面的属性什么的,这个时候我们可以在这个需要被调用属性脚本里面写一个单例模式。可项目大了需要被调用的脚本也就会很多,这个时候我们要是还像以前那样每个需要被调用的脚本里面就写一个单例模式,那样就太麻烦了。所以这里我们可以封装下这个单例模式。
写一个类:
public class Singleton<T> where T :new(){
protected static T sInstance = default(T);
public static T GetInstance(){
if (sInstance == null) {
sInstance = new T();
}
return sInstance;
}
}
然后在需要调用单例的地方写成:
public class EventCenter : Singleton<EventCenter>{
}
这样我们这个EventCenter这个脚本就是单例了。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。