Unity3D:C#扩展方法,扩展Unity3D没有方法

大腿Plus 2017年2月20日22:07:54Unity3D之项目开发评论1,062阅读模式

之前一直遇到某些功能没有,都要自己去写,前一阵子,用了DOTween动画插件,它里面所有方法都是通过C#扩展来实现的,中间在做项目的时候,老是遇到想用某个功能没有,都要去写,后来想到用扩展的方法写好某个功能,以后就能经常用到,用起来也会很方便。下面就直接上代码。文章源自大腿Plus-https://www.shijunzh.com/archives/387

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.shijunzh.com/archives/387

下面是上面方法打印的东西:文章源自大腿Plus-https://www.shijunzh.com/archives/387

Unity3D:C#扩展方法,扩展Unity3D没有方法

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

大腿Plus
  • 本文由 发表于 2017年2月20日22:07:54
  • 转载请务必保留本文链接:https://www.shijunzh.com/archives/387

发表评论