码迷,mamicode.com
首页 > 编程语言 > 详细

Unity3d中封装单例模式,Singleton

时间:2015-08-20 15:33:40      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:单例模式封装

  很多时候我们需要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这个脚本就是单例了。

本文出自 “酷酷小乔” 博客,请务必保留此出处http://5152481.blog.51cto.com/5142481/1686353

Unity3d中封装单例模式,Singleton

标签:单例模式封装

原文地址:http://5152481.blog.51cto.com/5142481/1686353

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!