一种是alpha检测

一种是设置collider

参考:

https://zhuanlan.zhihu.com/p/34204396

 

下面给出第二种方案代码

///按钮多边形点击方案,注意Canvas模式应该是Screen Space - Camera 需设置 Render Camera

///选中按钮右键UI->变更为多边形按钮,编辑子物体的Collider2D即可

///如果无法编辑Collider 则是Unity编辑器bug 切换下Unity编辑器的布局模式,即可恢复正常

using UnityEngine;

using UnityEngine.UI;

#if UNITY_EDITOR

using UnityEditor;

#endif

[RequireComponent(typeof(PolygonCollider2D))]

public class NonRectangularButtonImage : Image

{

private PolygonCollider2D areaPolygon;

protected NonRectangularButtonImage()

{

useLegacyMeshGeneration = true;

}

private PolygonCollider2D Polygon

{

get

{

if (areaPolygon != null)

return areaPolygon;

areaPolygon = GetComponent();

return areaPolygon;

}

}

protected override void OnPopulateMesh(VertexHelper vh)

{

vh.Clear();

}

public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)

{

return Polygon.OverlapPoint(eventCamera.ScreenToWorldPoint(screenPoint));

}

#if UNITY_EDITOR

protected override void Reset()

{

base.Reset();

transform.localPosition = Vector3.zero;

var w = rectTransform.sizeDelta.x * 0.5f + 0.1f;

var h = rectTransform.sizeDelta.y * 0.5f + 0.1f;

Polygon.points = new[]

{

new Vector2(-w, -h),

new Vector2(w, -h),

new Vector2(w, h),

new Vector2(-w, h)

};

}

#endif

}

#if UNITY_EDITOR

[CustomEditor(typeof(NonRectangularButtonImage), true)]

public class CustomRaycastFilterInspector : Editor

{

public override void OnInspectorGUI()

{

}

}

public class NonRectAngularButtonImageHelper

{

[MenuItem("GameObject/UI/变更为多边形按钮")]

public static void CreateNonRectAngularButtonImage()

{

var goRoot = Selection.activeGameObject;

if (goRoot == null)

return;

var button = goRoot.GetComponent