using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; #endif [RequireComponent(typeof(PolygonCollider2D))] public class UIPolygon : Image { private PolygonCollider2D _polygon = null; private PolygonCollider2D polygon { get { if (_polygon == null) _polygon = GetComponent<PolygonCollider2D>(); return _polygon; } } //设置只响应点击,不进行渲染 protected UIPolygon() { useLegacyMeshGeneration = true; } protected override void OnPopulateMesh(VertexHelper toFill) { toFill.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.position = Vector3.zero; float w = (rectTransform.sizeDelta.x * 0.5f) + 0.1f; float h = (rectTransform.sizeDelta.y * 0.5f) + 0.1f; polygon.points = new Vector2[] { new Vector2(-w,-h), new Vector2(w,-h), new Vector2(w,h), new Vector2(-w,h) }; } #endif #if UNITY_EDITOR [CustomEditor(typeof(UIPolygon), true)] public class UIPolygonInspectorGUI : Editor { public override void OnInspectorGUI() { } } #endif }
把按钮的Image组件和Text组件的Raycast Target取消勾选,在Button下新建一个空物体添加UIPolygon脚本,标记好点击区域就好了。注意,这一检测点击需要使用到相机,所以Canvas的Render Mode要选择相机模式,所用的相机使用正交模式,不然多边形点击区域就会不准了。