寫更少代碼的需求
當我們重複寫一些繁雜的代碼,或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#的方法
public static T CFirstOrDefault<T>(this IEnumerable<T> source)
{
if (source != null)
{
foreach (T item in source)
{
return item;
}
}
return default(T);
}