我们在制作UGUI的时候经常会遇到需要精准点击不规则按钮或有部分透明区域的按钮的情况,但如果是正常创建Button的话,空白区域也会响应点击事件,如下:  这时候我们就能通过设置一些参数,来不响应透明区域的点击。
一、设置资源参数 开启资源的Read/Write Enabled  二、代码设置按钮Image的alphaHitTestMinimumThreshold 获取按钮控件下的Image脚本,设置Image脚本的alphaHitTestMinimumThreshold参数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestButtonClick : MonoBehaviour
{
private Button m_TestBtn;
private Image m_TestImage;
private void Awake()
{
m_TestBtn = this.transform.GetComponent<Button>();
m_TestImage = this.transform.GetComponent<Image>();
m_TestBtn.onClick.AddListener(ButtonClick);
m_TestImage.alphaHitTestMinimumThreshold = 0.1f;
}
private void ButtonClick()
{
Debug.LogError("点击TestBtn");
}
}
三、最终效果  这样设置后,点击透明区域就不会响应点击事件啦
|