using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
/// <summary>
/// 解决嵌套使用ScrollRect时的Drag冲突问题。请将该脚本放置到内层ScrollRect上(外层的ScrollRect的Drag事件会被内层的拦截)
/// </summary>
public class MultiScroll : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[SerializeField]
private ScrollRect scroll_parent;
private ScrollRect scroll_this;
private float angle;
[SerializeField]
private bool horizontalOrVertical;
private bool direction;
void Awake()
{
scroll_this = GetComponent<ScrollRect>();
if (scroll_parent == null)
scroll_parent = GetComponentsInParent<ScrollRect>()[1];
}
public void OnBeginDrag(PointerEventData eventData)
{
scroll_parent.OnBeginDrag(eventData);
}
public void OnDrag(PointerEventData eventData)
{
scroll_parent.OnDrag(eventData);
//判断拖动方向,防止水平与垂直方向同时响应导致的拖动时整个界面都会动
angle = Vector2.Angle(eventData.delta, Vector2.up);
direction = angle > 45f && angle < 135f;
if (direction)
{
//Horizontal
scroll_parent.enabled = !horizontalOrVertical;
scroll_this.enabled = horizontalOrVertical;
}
else
{
//Vertical
scroll_this.enabled = !horizontalOrVertical;
scroll_parent.enabled = horizontalOrVertical;
}
}
public void OnEndDrag(PointerEventData eventData)
{
scroll_parent.OnEndDrag(eventData);
scroll_parent.enabled = true;
scroll_this.enabled = true;
}
}
}