1. 程式人生 > >【Unity3d】UGUI小貼士:使用不規則按鈕

【Unity3d】UGUI小貼士:使用不規則按鈕

在平時的遊戲和平面程式開發中,難免會遇到需要使用不規則按鈕的需求,而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:
Read/Write Enbale


然後新建一個指令碼,命名為IrregularButton,開啟在Awake或者Start方法中輸入如下程式碼:

    Image image = GetComponent<Image>();
    image.alphaHitTestMinimumThreshold = 0.1f;
  • 1
  • 2

程式碼第一行獲取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 + "次按下按鈕"; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

專案原始碼(開發環境unity3d 5.5.0f3):
百度網盤
提取碼:ee97