GameObject是sealed class 不可繼承,但是C#給我們提供了一個更加輕便的辦法去擴展一個類——靜態擴展
“擴展方法使您能夠向現有類型“添加”方法,而無需創建新的派生類型、重新編譯或以其他方式修改原始類型。”——msdn
直接上代碼
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YieldTest
{
class Program
{
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s.StringLength());
}
}
static class MyString
{
public static int StringLength(this string s)
{
return s.Length;
}
}
}
擴展unity GameObject
達到如下效果:
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);
}
...
}