擴展Unity的方法


寫更少代碼的需求

當我們重復寫一些繁雜的代碼,或C#的一些方法,我們就想能不能有更便捷的方法呢?當然在unity中,我們對它進行擴展。

對unity的類或C#的類進行擴展有以下兩點要注意:

1、這個類必須聲明為static,擴展的方法也必須要聲明為static

2、在使用時,就可以直接調用擴展的方法

擴展Unity的屬性

Demo

using UnityEngine;
using System.Collections;

//It is common to create a class to contain all of your
//extension methods. This class must be static.
public static class ExtensionMethods
{
    //Even though they are used like normal methods, extension
    //methods must be declared static. Notice that the first
    //parameter has the 'this' keyword followed by a Transform
    //variable. This variable denotes which class the extension
    //method becomes a part of.
    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

 

使用方法

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        //Notice how you pass no parameter into this
        //extension method even though you had one in the
        //method declaration. The transform object that
        //this method is called from automatically gets
        //passed in as the first parameter.
        transform.ResetTransformation();
    }
}

擴展C#的方法

為C#的集合擴展一個方法,當在調用時,就可以直接調用CFirstOrDefault

public static T CFirstOrDefault<T>(this IEnumerable<T> source)
{
    if (source != null)
    {
        foreach (T item in source)
        {
            return item;
        }
    }

    return default(T);
}

文檔資料

文檔:http://unity3d.com/learn/tutorials/modules/intermediate/scripting/extension-methods


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM