多语言展示
当前在线:1157今日阅读:61今日分享:18

Unity UI技巧 之 快速学会Button不规则按钮处理

Unity UI技巧 之 快速学会Button不规则按钮处理。在平时的游戏和平面程序开发中,难免会遇到需要使用不规则按钮的需求,而Unity3d中使用UGUI的Button控件只能实现规则的长方形按钮。不过其实unity的Image提供了一个eventAlphaThreshold的属性(在5.4以上版本中改为alphaHitTestMinimumThreshold),这个属性提供了一个阈值来限制射线检测生效的alpha值。也就是说,比如我们将阈值设为0.5(该值类型为float,有效范围0到1),那么点击Image上像素的alpha值小于0.5的区域时,程序是不会检测到点击事件的,本节讲解如何实现不规则按钮的处理方法的使用,具体如下
工具/原料
1

Unity

2

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.

二、UI技巧 之 快速学会Button不规则按钮处理
1

打开Unity,新建一个空工程,然后Unity界面如下图

2

在工程中新建一个脚本,脚本可以命名为“ButtonTest”,具体如下图

3

选中脚本“ButtonTest”,双击脚本或者右键“Open C# Project”,打开脚本,具体如下图

4

在打开的脚本上进行代码编辑,首先设定一个Image变量,然后赋值Image变量,并且设置图片的alphaHitTestMinimumThreshold值不为1,具体根据自己的需要调整,具体代码和代码说明如下图

5

脚本编译正确后,回到Unity界面,在场景中新建一个“Button”,并把脚本“ButtonTest”赋给“Button”,具体如下图

6

导入一个不规则图片,设置该图片的“Texture Type”为“Sprite(2D and UI)”,并且勾选上“Read/Write Enabled”,然后“Apply”,具体如下图

7

把图片赋值给“Button”里面的“Image”,具体如下图

8

在新建一个“Button”,把图片也赋给它,但是“ButtonTest”不赋给它,就改变它图片的alphaHitTestMinimumThreshold值(默认值为1),以作为对比,具体如下图

9

运行场景,即可看到,改变了图片的alphaHitTestMinimumThreshold值的按钮图片外“Button”边缘点击不了(即左边按钮);没有改变了图片的alphaHitTestMinimumThreshold值的按钮图片外“Button”边缘能正常点击(即右边按钮),具体如下图

10

到此,《Unity UI技巧 之 快速学会Button不规则按钮处理》讲解结束,谢谢

注意事项
1

需要注意的是,使用alphaHitTestMinimumThreshold属性需要开启sprite的Read/Write Enbale属性,这样程序就会在内存中多存一份sprite,内存占用也就翻了一番,所以不太适合移动端大量按钮的使用

2

更多信息可以参考Unity Manual手册

3

若帮到您,还请帮忙投票以帮助到更多的人;若有疑问,请留言

推荐信息