通过扩展方法简化UnityAPI调用


通过扩展方法简化UnityAPI调用

扩展方法unity apiapi简化

通过扩展方法简化UnityAPI调用

能省一秒是一秒,时间就是金钱,没人愿意把时间花在冗长的coding上??

定义扩展方法简化Transform中对位置的赋值

  1. using UnityEngine; 
  2. namespace WSFramework
  3. public static class TransformLocalPosImprovements
  4. public static void SetLocalPosX (this Transform transform, float x)
  5. var localPos = transform.localPosition; 
  6. localPos.x = x; 
  7. transform.localPosition = localPos; 
  8. public static void SetLocalPosY (this Transform transform, float y)
  9. var localPos = transform.localPosition; 
  10. localPos.y = y; 
  11. transform.localPosition = localPos; 
  12. public static void SetLocalPosZ (this Transform transform, float z)
  13. var localPos = transform.localPosition; 
  14. localPos.z = z; 
  15. transform.localPosition = localPos; 
  16. public static void SetLocalPosXY (this Transform transform, float x, float y)
  17. var localPos = transform.localPosition; 
  18. localPos.x = x; 
  19. localPos.y = y; 
  20. transform.localPosition = localPos; 
  21. public static void SetLocalPosXZ (this Transform transform, float x, float z)
  22. var localPos = transform.localPosition; 
  23. localPos.x = x; 
  24. localPos.z = z; 
  25. transform.localPosition = localPos; 
  26. public static void SetLocalPosYZ (this Transform transform, float y, float z)
  27. var localPos = transform.localPosition; 
  28. localPos.y = y; 
  29. localPos.z = z; 
  30. transform.localPosition = localPos; 
  31.  
  32. ///  
  33. /// 重置操作 
  34. ///  
  35. /// Trans. 
  36. public static void Identity (this Transform transform)
  37. transform.localPosition = Vector3.zero; 
  38. transform.localScale = Vector3.one; 
  39. transform.localRotation = Quaternion.identity; 

不使用扩展方法和使用扩展方法的比较

想想曾经在localPosition赋值上浪费了多少时间,扩展方法定让你爱不释手??

  1. using System.Collections; 
  2. using System.Collections.Generic; 
  3. using UnityEngine; 
  4. using WSFramework; 
  5.  
  6. public class Test : MonoBehaviour 
  7. public Transform target; 
  8.  
  9. // Start is called before the first frame update 
  10. void Start() 
  11. Invoke("CustomSetPosA",2f); 
  12. Invoke("CustomSetPosB",4f); 
  13. Invoke("ExtentionSetPos", 6f); 
  14.  
  15. //--普通方法调用 
  16. void CustomSetPosA() 
  17. //--三行,龟龟 
  18. var pos = target.localPosition; 
  19. pos.x = 2.0f; 
  20. target.localPosition = pos; 
  21.  
  22. //-- 普通方法调用 
  23. void CustomSetPosB() 
  24. //--localposition ... ... 
  25. target.localPosition=new Vector3(target.localPosition.x,target.localPosition.y,2.0f); 
  26.  
  27. //--扩展方法调用 
  28. void ExtentionSetPos() 
  29. target.SetLocalPosX(0f); 
  30.  

推荐一个非常好用的编辑器扩展插件,简单的添加attribute标签就可以实现需要editor下繁琐代码实现的功能,很方便的进行测试啥的,也可以利用它的接口实现自己的编辑器工具。