本篇原本是做爲原來 優雅的QChain的第一篇的內容,可是QChain流產了,因此收錄到了遊戲框架搭建系列。本篇介紹如何實現GameObject的鏈式編程。git
鏈式編程的實現技術之一是C#的靜態擴展。靜態擴展能夠作到無需繼承GameObject就能夠爲GameObject的對象添加成員方法。其實這麼說不太嚴謹,可是看起來就是這樣:)github
首先咱們要實現給GameObject添加一個DestroySelf方法。使用方式以下:編程
gameObject.DestroySelf();
貼上具體實現代碼 :c#
using System; using UnityEngine; /// <summary> /// GameObject's Util/This Extension /// </summary> public static class GameObjectExtension { ... public static void DestroySelf(this GameObject selfObj) { GameObject.Destroy(selfObj); } ... }
代碼很是簡單。微信
以上代碼要注意的是:框架
固然也能夠用這種方式使用:ide
GameObjectExtension.DestroySelf(gameObject);
這樣寫的意義不大,不如直接用Object/GameObject.Destroy(gameObject);不過也有可使用的情形,就是當導出給腳本層使用的時候。這裏很少說。
初步入門就介紹到這裏。下面實現鏈式編程。性能
鏈式編程實現方式多種多樣。可是對於GameObject來講有一種最簡單而且最合適的方法,就是靜態擴展 + 返回this的方式。this
爲何呢?鏈式編程若是可使用繼承實現的話有不少種玩法,只不過GameObject是sealed class,不能被繼承。因此只能經過靜態擴展 + 返回this的方式。這也是爲何會把這篇文章做爲第一篇的緣由。設計
先看下如何使用。
gameObject.Show() // active = true .Layer(0) // layer = 0 .Name("Example"); // name = "Example"
接下來貼出實現:
using System; using UnityEngine; /// <summary> /// GameObject's Util/This Extension /// </summary> public static class GameObjectExtension { public static GameObject Show(this GameObject selfObj) { selfObj.SetActive(true); return selfObj; } public static GameObject Hide(this GameObject selfObj) { selfObj.SetActive(false); return selfObj; } public static GameObject Name(this GameObject selfObj,string name) { selfObj.name = name; return selfObj; } public static GameObject Layer(this GameObject selfObj, int layer) { selfObj.layer = layer; return selfObj; } public static void DestroySelf(this GameObject selfObj) { GameObject.Destroy(selfObj); } ... }
能夠看到新增的幾個靜態方法與DestroySelf不一樣的是,多了個return selfObj,就是調用方法時返回本身,這樣能夠接着調用本身的方法。原理很簡單。
執行效率 vs 開發效率 + 低bug率,就看各位怎麼權衡啦。
OK,本篇就介紹到這裏。
QFramework地址:https://github.com/liangxiegame/QFramework
轉載請註明地址:涼鞋的筆記http://liangxiegame.com/
微信公衆號:liangxiegame