Unity 不规则按钮点击实现方案

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class PolygonImage : Image, IPointerEnterHandler, IPointerExitHandler
{

    private PolygonCollider2D m_PolygonCollider2D;


    public PolygonCollider2D PolygonCollider2D
    {
        get
        {
            return gameObject.GetOrAddComponent<PolygonCollider2D>();

        }

        private set { }
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        
    }

    public void OnPointerExit(PointerEventData eventData)
    {
       
    }



    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        Vector3 point;

        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, eventCamera, out point);

        return PolygonCollider2D.OverlapPoint(point);
    }
}

public static class MonoExtend
{
    public static T GetOrAddComponent<T>(this GameObject obj)where T:Component
    {

        if(obj.GetComponent<T>()==null)
        {
            return obj.AddComponent<T>();
        }

        return  obj.GetComponent<T>();
    }
}

 创建Button  删除掉Button上面自带的Image ,把这个Image 挂在上,添加PolygonCollider2D 组件,根据需要绘制自己的形状 ,就ok了

 


版权声明:本文为L877790502原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。