美文网首页Unity3D与游戏开发征服Unity3dUnity基础入门分享
UGUI使用小技巧(四)给不规则按钮添加点击事件

UGUI使用小技巧(四)给不规则按钮添加点击事件

作者: 不文不武的禾文 | 来源:发表于2020-01-04 00:02 被阅读0次

    UGUI中的Button都是矩形的,但是在项目中,也会遇到不规则图形的按钮(比如做地图),如果给你一张不规则的图形,按普通的矩形按钮做,图形以外的区域也会添加上点击事件,怎么给不规则的按钮添加点击事件呢,这里介绍两种方法:

    方法一:

    修改不规则按钮的Image组件中的的alphaHitTestMinimumThreshold属性。

    public class Test : MonoBehaviour {
    
        public Image image;
        public float test = 0.5f;
        // Use this for initialization
        void Start () {
            image.alphaHitTestMinimumThreshold = test;
        }
    }
    
    
    image.gif

    再修改图片的Read/Write Enabled属性为true,这样的话,只有alpha大于设置的值时,才会响应点击事件。

    这个解决方案有两个缺点。

    1、图片在导入时需要开启Readable/Write Enable属性,使运行时图片大小变大, 增大内存开销。

    2、如果不规则区域外的alpha值不低于设置值的透明值则不能使用,比如图片的alpha值都是1。

    方法二:

    继承Image,重写IsRaycastLocationValid方法,利用PolygonCollider2D自定义按钮的点击区域。

    using UnityEngine;
    using UnityEngine.UI;
    
    public class PolygonImage : Image
    {
        private Collider2D _collider2D = null;
        private Collider2D UICollider2D
        {
            get
            {
                if (_collider2D == null)
                    _collider2D = GetComponent<Collider2D>();
                return _collider2D;
            }
        }
        #region 优化  (透明的Image 也会持续的早成绘制的开销。)
        protected PolygonImage()
        {
            useLegacyMeshGeneration = true;
            raycastTarget = false;//默认关闭射线检测
        }
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
        }
        #endregion
    
        public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
        {
            if (UICollider2D != null)
            {
                return UICollider2D.OverlapPoint(eventCamera.ScreenToWorldPoint(screenPoint));
            }
            else
            {
                return base.IsRaycastLocationValid(screenPoint, eventCamera);
            }
        }
    }
    
    image.gif

    相关文章

      网友评论

        本文标题:UGUI使用小技巧(四)给不规则按钮添加点击事件

        本文链接:https://www.haomeiwen.com/subject/hrtaoctx.html