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;

    /// 
    /// GameObject's Util/This Extension
    /// 
    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);
        }
          ...
}

参考

凉鞋笔记

你可能感兴趣的:(unity,unity,GameObject,方法扩展)