您的位置:首页 > 其它

总结1_3:扩展方法与单例

2017-12-06 18:35 405 查看
撸代码总纲:最少的代码,最稳的框架,最优的逻辑

一、扩展方法的出现,大大简化了代码量

类似于GetComponent,而且,我们自定义的扩展方法,还可以根据需求在里面添加一些必要的逻辑。

//扩展方法
//静态类->静态方法->参数列表第一个为:this 类型 形参
public static class ExpandClass {

/// <summary>
/// 获取到实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T GetInstance<T>(this T t,string s) where T : new()
{
if (t == null)
{
t = new T();
}
UnityEngine.Debug.Log(s);
return t;
}
}


测试

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

public class ExpandTest : MonoBehaviour {
List<string> listA;
// Use this for initialization
void Start () {
List<string> listB = listA.GetInstance("listB");
List<string> listC = listA;
string msg1 = listB == null ? "listB is null,bad method!" : "listB isn't null,good method!";
string msg2 = listC == null ? "listC is nul
4000
l,please assignment!" : "listC isn't null,go!";
OnDebug(msg1);
OnDebug(msg2);
}
void OnDebug(string msg)
{
Debug.Log("Result: " + msg);
}
}


结果



二、 继承自MonoBehaviour的泛型单例

(转载出处: http://blog.csdn.net/honey199396/article/details/48827955 unity3D – 单例泛型模板)

满足的需求:a、保证能通过代码直接获取到脚本实例; b、该脚本实例在场景中唯一; c、该脚本能用UnityEngine中内置的方法(Start,Update等)

泛型单例

using UnityEngine;

public class SingleTon<T>: MonoBehaviour where T :MonoBehaviour {
private static T instance;//实例设为private,较好的封装性
private static object lockThread = new object();//线程锁,保护数据安全
private static bool isQuit = false;//被销毁之后,类型无实例
public static T GetInstance//通过属性获取实例
{
get
{
if (isQuit)
{
return null;
}
lock (lockThread)
{
if (instance == null)
{
instance = (T)Object.FindObjectOfType(typeof(T)); //先查找,没有再new一个游戏对象,Add
if (Object.FindObjectsOfType(typeof(T)).Length > 1)
{
Debug.LogWarning("Too many " + typeof(T).ToString());//如果不止一个实例,警告一下,返回第一个
return instance;
}
if (instance == null)
{
GameObject singleTon = new GameObject("SingleTon",typeof(T));
instance = singleTon.GetComponent<T>();
DontDestroyOnLoad(singleTon); //加载不销毁,看需求,此句可以干掉
}
}
return instance;
}
}
}
public static void OnDestroy()
{
isQuit = true;
}
}


实际需要的单例类

可挂可不挂

using UnityEngine;

public class SingleTonTest : SingleTon<SingleTonTest> {

//只是测试,如果该方法被调用,就输出一下
public void OnPrint()
{
Debug.Log(typeof(SingleTonTest).ToString());
}
}


其他类对单例类的调用

挂在游戏对象上

using UnityEngine;

public class SingleTonTest1 : MonoBehaviour{

public void Start()
{
SingleTonTest.GetInstance.OnPrint();
}
}


测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: