之前一直遇到某些功能没有,都要自己去写,前一阵子,用了DOTween动画插件,它里面所有方法都是通过C#的扩展来实现的,中间在做项目的时候,老是遇到想用某个功能没有,都要去写,后来想到用扩展的方法写好某个功能,以后就能经常用到,用起来也会很方便。下面就直接上代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using UnityEngine; using UnityEngine.UI; public class MyClass : MonoBehaviour { private bool[] values = { false, true, true, false, true }; public Image trans; // Use this for initialization void Start() { int count = values.GetValueCount(true); Debug.Log("数组中True的个数为:" + count); string str = trans.GetImageName(); Debug.Log("Image的名字是:" + str); } // Update is called once per frame void Update() { } } public static class BooleanArray { public static int GetValueCount(this bool[] values, bool value) { int count = 0; for (int i = 0; i < values.Length; i++) { if (values[i] == value) { count++; } } return count; } } public static class ExtensionMethods { public static string GetImageName(this Image go) { return go.name; } } |
对unity的类或C#的类进行扩展有以下两点要注意:
1、这个类必须声明为static,扩展的方法也必须要声明为static。
2、在使用时,就可以直接调用扩展的方法。文章源自大腿Plus-https://www.zhaoshijun.com/archives/387
下面是上面方法打印的东西:文章源自大腿Plus-https://www.zhaoshijun.com/archives/387

还可以扩展很多东西,使用起来也很方便,只要变量点就能直接调用这个方法。这个类名可以是任意的,只要方法里this后面的是你要扩展的组件或者其他类都可以。有什么不明白的可以留言,有空的话我一定会解答的。文章源自大腿Plus-https://www.zhaoshijun.com/archives/387 文章源自大腿Plus-https://www.zhaoshijun.com/archives/387
我的微信
微信扫一扫

shijun_z
我的QQ
QQ扫一扫

846207670
评论