通过扩展方法简化UnityAPI调用
通过扩展方法简化UnityAPI调用
扩展方法unity apiapi简化通过扩展方法简化UnityAPI调用
能省一秒是一秒,时间就是金钱,没人愿意把时间花在冗长的coding上??
定义扩展方法简化Transform中对位置的赋值
- using UnityEngine;
- namespace WSFramework {
- public static class TransformLocalPosImprovements {
- public static void SetLocalPosX (this Transform transform, float x) {
- var localPos = transform.localPosition;
- localPos.x = x;
- transform.localPosition = localPos;
- }
- public static void SetLocalPosY (this Transform transform, float y) {
- var localPos = transform.localPosition;
- localPos.y = y;
- transform.localPosition = localPos;
- }
- public static void SetLocalPosZ (this Transform transform, float z) {
- var localPos = transform.localPosition;
- localPos.z = z;
- transform.localPosition = localPos;
- }
- public static void SetLocalPosXY (this Transform transform, float x, float y) {
- var localPos = transform.localPosition;
- localPos.x = x;
- localPos.y = y;
- transform.localPosition = localPos;
- }
- public static void SetLocalPosXZ (this Transform transform, float x, float z) {
- var localPos = transform.localPosition;
- localPos.x = x;
- localPos.z = z;
- transform.localPosition = localPos;
- }
- public static void SetLocalPosYZ (this Transform transform, float y, float z) {
- var localPos = transform.localPosition;
- localPos.y = y;
- localPos.z = z;
- transform.localPosition = localPos;
- }
- ///
- /// 重置操作
- ///
- /// Trans.
- public static void Identity (this Transform transform) {
- transform.localPosition = Vector3.zero;
- transform.localScale = Vector3.one;
- transform.localRotation = Quaternion.identity;
- }
- }
- }
不使用扩展方法和使用扩展方法的比较
想想曾经在localPosition赋值上浪费了多少时间,扩展方法定让你爱不释手??
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using WSFramework;
- public class Test : MonoBehaviour
- {
- public Transform target;
- // Start is called before the first frame update
- void Start()
- {
- Invoke("CustomSetPosA",2f);
- Invoke("CustomSetPosB",4f);
- Invoke("ExtentionSetPos", 6f);
- }
- //--普通方法调用
- void CustomSetPosA()
- {
- //--三行,龟龟
- var pos = target.localPosition;
- pos.x = 2.0f;
- target.localPosition = pos;
- }
- //-- 普通方法调用
- void CustomSetPosB()
- {
- //--localposition ... ...
- target.localPosition=new Vector3(target.localPosition.x,target.localPosition.y,2.0f);
- }
- //--扩展方法调用
- void ExtentionSetPos()
- {
- target.SetLocalPosX(0f);
- }
- }
推荐一个非常好用的编辑器扩展插件,简单的添加attribute标签就可以实现需要editor下繁琐代码实现的功能,很方便的进行测试啥的,也可以利用它的接口实现自己的编辑器工具。