在平时的游戏和平面程序开发中,难免会遇到需要使用不规则按钮的需求,而Unity3D中使用UGUI的Button控件只能实现规则的长方形按钮。不过其实unity的Image提供了一个eventAlphaThreshold的属性(在5.4以上版本中改为alphaHitTestMinimumThreshold),这个属性提供了一个阈值来限制射线检测生效的alpha值。也就是说,比如我们将阈值设为0.5(该值类型为float,有效范围0到1),那么点击Image上像素的alpha值小于0.5的区域时,程序是不会检测到点击事件的。
利用这一个属性,我们就可以实现不规则按钮了。但是需要注意的是,使用alphaHitTestMinimumThreshold属性需要开启sprite的Read/Write Enbale属性,这样程序就会在内存中多存一份sprite,内存占用也就翻了一番,所以不太适合移动端大量按钮的使用。
首先我们导入图片资源,然后转换成Sprite类型,这里5.5以下的版本需要再把类型改成Advanced。然后勾选Read/Write Enbale:

然后新建一个脚本,命名为IrregularButton,打开在Awake或者Start方法中输入如下代码:
    Image image = GetComponent<Image>();
    image.alphaHitTestMinimumThreshold = 0.1f;
代码第一行获取button控件的image,第二行将image的alpha阈值设置为0.1。然后我们写一个方法,每次按下按钮时就进行一次计数并显示,来测试是否按钮为不规则按钮。程序运行效果如下:

完整的代码:

IrregularButton.cs:

using UnityEngine;
using UnityEngine.UI;
public class IrregularButton : MonoBehaviour
{
    public Text text;
    private int count;
    void Awake ()
    {
        // 设置阈值
        Image image = GetComponent<Image>();
        image.alphaHitTestMinimumThreshold = 0.1f;
        count = 0;
    }
    public void OnButtonClicked()
   {
        count++;
        text.text = "第" + count + "次按下按钮";
    }
}