先看效果:
结构:
代码:
using DG.Tweening;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Page1_Index : MonoBehaviour, IPointerExitHandler
{
private ScrollRect scrollView;
private RectTransform content;
private int pageMaxIndex = 3;
private int currentIndex = 0;
private bool isComponentsInited = false;
private bool isStarted = false;
private int screenWidth = 1920;
public void OnPointerExit(PointerEventData eventData)
{
float deltaX = screenWidth * 0.1f;
if (currentIndex == 0)
{
if (content.anchoredPosition.x < -deltaX)
{
currentIndex = 1;
}
}
else if (currentIndex == pageMaxIndex)
{
if (content.anchoredPosition.x > -screenWidth * currentIndex + deltaX)
{
currentIndex--;
}
}
else
{
//处理大于2张的情况
if (content.anchoredPosition.x > -screenWidth * currentIndex + deltaX)
{
currentIndex--;
}
else if (content.anchoredPosition.x < -screenWidth * currentIndex - deltaX)
{
currentIndex++;
}
}
int targetX = -currentIndex * screenWidth;
content.DOAnchorPosX(targetX, 0.5f);
}
private void Start()
{
scrollView = transform.Find("ScrollView").GetComponent<ScrollRect>();
content = transform.Find("ScrollView/Viewport/Content").GetComponent<RectTransform>();
isComponentsInited = true;
content.anchoredPosition = Vector2.zero;
currentIndex = 0;
isStarted = true;
}
private void OnEnable()
{
if (isComponentsInited && !isStarted)
{
content.anchoredPosition = Vector2.zero;
currentIndex = 0;
isStarted = true;
}
}
private void Update()
{
if (content.anchoredPosition.x > 0)
{
content.anchoredPosition = Vector2.zero;
}
else if (content.anchoredPosition.x < -screenWidth * pageMaxIndex)
{
content.anchoredPosition = new Vector2(-screenWidth * pageMaxIndex, 0);
}
}
}
适配注意事项:
1.canvas设置
2. screenWidth = 1920,即这里就等于canvas里设置的屏幕宽度,而不能在start函数里动态获取屏幕宽度:screenWidth = Screen.Width,我就踩了这个坑,自以为是适配不同分辨率,但恰恰相反
3. 所有位置判断和移动的距离,都依据1920这个值(制作分辨率宽度)
不得不说Unity的UGUI分辨率适配做得的确简介,一次开发,多屏适配,给它点个赞