unity靜態擴展GameObject

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);
        }
          ...
}

參考

涼鞋筆記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章