經常忘記如何做 Extend method.筆記一下.
using UnityEngine; using System.Collections; namespace Kit.Vector3Ext { public static class Vector3Ext { /// <summary>Assign vector3.x</summary> /// <param name="x">The x coordinate.</param> public static void SetX(this Vector3 _this, float x) { _this.x = x; } /// <summary>Assign vector3.y</summary> /// <param name="y">The y coordinate.</param> public static void SetY(this Vector3 _this, float y) { _this.y = y; } /// <summary>Assign vector3.z</summary> /// <param name="z">The z coordinate.</param> public static void SetZ(this Vector3 _this, float z) { _this.z = z; } /// <summary>Clamp Vector3.x value.</summary> /// <param name="_min">_min.</param> /// <param name="_max">_max.</param> public static void ClampX(this Vector3 _this, float _min, float _max) { _this.x = Mathf.Clamp(_this.x, _min, _max); } /// <summary>Clamp Vector3.x value.</summary> /// <param name="_min">_min.</param> /// <param name="_max">_max.</param> public static void ClampY(this Vector3 _this, float _min, float _max) { _this.y = Mathf.Clamp(_this.y, _min, _max); } /// <summary>Clamp Vector3.x value.</summary> /// <param name="_min">_min.</param> /// <param name="_max">_max.</param> public static void ClampZ(this Vector3 _this, float _min, float _max) { _this.z = Mathf.Clamp(_this.z, _min, _max); } } }
重點是
- static class
- static function
- function input, first parameter = this,
而功效就是,於程序中宣告了 using Kit.Vector3Ext 後, 即可以用任何已宣告的 Vector3 variable 中調用相關的 class.
Vector3 _test = Vector3.zero; _text.SetX(10f); // Vector3 = {10f,0f,0f} _text.SetY(20f); // Vector3 = {10f,20f,0f} _text.SetZ(30f); // Vector3 = {10f,20f,30f} _text.ClampX(1f,5f); // Vector3 = {5f,20f,30f} _text.ClampY(5f,10f); // Vector3 = {5f,10f,30f} _text.ClampZ(1f,5f); // Vector3 = {5f,10f,5f}