Unity
UGUI Button
Image.alphaHitTestMinimumThreshold:The alpha threshold specifies the minimum alpha a pixel must have for the event to considered a 'hit' on the Image.Alpha values less than the threshold will cause raycast events to pass through the Image. An value of 1 would cause only fully opaque pixels to register raycast events on the Image. The alpha tested is retrieved from the image sprite only, while the alpha of the Image Graphic.color is disregarded.alphaHitTestMinimumThreshold defaults to 0; all raycast events inside the Image rectangle are considered a hit. In order for greater than 0 to values to work, the sprite used by the Image must have readable pixels. This can be achieved by enabling Read/Write enabled in the advanced Texture Import Settings for the sprite and disabling atlassing for the sprite.
打开Unity,新建一个空工程,然后Unity界面如下图
在工程中新建一个脚本,脚本可以命名为“ButtonTest”,具体如下图
选中脚本“ButtonTest”,双击脚本或者右键“Open C# Project”,打开脚本,具体如下图
在打开的脚本上进行代码编辑,首先设定一个Image变量,然后赋值Image变量,并且设置图片的alphaHitTestMinimumThreshold值不为1,具体根据自己的需要调整,具体代码和代码说明如下图
脚本编译正确后,回到Unity界面,在场景中新建一个“Button”,并把脚本“ButtonTest”赋给“Button”,具体如下图
导入一个不规则图片,设置该图片的“Texture Type”为“Sprite(2D and UI)”,并且勾选上“Read/Write Enabled”,然后“Apply”,具体如下图
把图片赋值给“Button”里面的“Image”,具体如下图
在新建一个“Button”,把图片也赋给它,但是“ButtonTest”不赋给它,就改变它图片的alphaHitTestMinimumThreshold值(默认值为1),以作为对比,具体如下图
运行场景,即可看到,改变了图片的alphaHitTestMinimumThreshold值的按钮图片外“Button”边缘点击不了(即左边按钮);没有改变了图片的alphaHitTestMinimumThreshold值的按钮图片外“Button”边缘能正常点击(即右边按钮),具体如下图
到此,《Unity UI技巧 之 快速学会Button不规则按钮处理》讲解结束,谢谢
需要注意的是,使用alphaHitTestMinimumThreshold属性需要开启sprite的Read/Write Enbale属性,这样程序就会在内存中多存一份sprite,内存占用也就翻了一番,所以不太适合移动端大量按钮的使用
更多信息可以参考Unity Manual手册
若帮到您,还请帮忙投票以帮助到更多的人;若有疑问,请留言