在unity中实现2层ScrollView的嵌套,两层的ScrollView的拖动方向不一样,这个功能的核心就是如何把子ScrollView事件传递给父ScrollView,在查阅资料之后发现只需要实现一下3个接口就行了
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// 解决2个层级的ScrollView嵌套但是方向不同的情况
/// </summary>
public class ScrollViewLayers : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
/// <summary>
/// 上层的ScrollRect
/// </summary>
ScrollRect parentScrollRect = null;
//事件传递
public void OnBeginDrag(PointerEventData eventData)
{
isCheckEnd = false;
if (shouldSendEvent)
{
parentScrollRect.OnBeginDrag(eventData);
}
}
//事件传递
public void OnDrag(PointerEventData eventData)
{
if (shouldSendEvent)
{
parentScrollRect.OnDrag(eventData);
}
if (isCheckEnd)
{
return;
}
isCheckEnd = true;
oldPos = Input.mousePosition;
StartCoroutine(Check());
}
//事件传递
public void OnEndDrag(PointerEventData eventData)
{
if (shouldSendEvent)
{
parentScrollRect.OnEndDrag(eventData);
}
}
void Start()
{
parentScrollRect = transform.parent.parent.parent.GetComponent<ScrollRect>();
}
//事件过滤
bool shouldSendEvent = false;
Vector3 oldPos = Vector3.zero;
bool isCheckEnd = false;
IEnumerator Check()
{
yield return new WaitForSeconds(Time.deltaTime);
Vector3 temp = Input.mousePosition - oldPos;
shouldSendEvent = temp.x * temp.x > temp.y * temp.y;
GetComponent<ScrollRect>().enabled = !shouldSendEvent;
}
}
上述的代码实现的功能不止有事件的传递,还实现了事件的类型过滤,控制player同时只能去拖动左右或者上下,和安卓一些源生app挺像的,但是unity好像没有类似的实现,就花了点时间自己写了个。