unity 可以点击翻页的滑栏
需要先导入DOTween插件
脚本非常简单,仅仅是加减运算而已
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class SelectTraget : MonoBehaviour
{
public Button Btn_Left;
public Button Btn_Right;
public Transform ReferencePoint;//参考位置(显示区域中央)
public Transform Content;//被移动物体
private int index;
public int Indexer
{
get
{
return index;
}
set
{
if (value < 0)
{
print("最左");
index = 0;
}
else if (value > Content.transform.childCount-1)
{
print("最右");
index = Content.transform.childCount - 1;
}
else
{
index = value;
//移动
float A = Content.GetChild(index).position.x - ReferencePoint.position.x;//差值;
Content.DOMoveX(Content.position.x - A, 1f);
}
print(index);
}
}
public void Awake()
{
Btn_Left = transform.Find("Btn_Left").GetComponent<Button>();
Btn_Right = transform.Find("Btn_Right").GetComponent<Button>();
Btn_Back = transform.parent.Find("Btn_Back").GetComponent<Button>();
Btn_Sure = transform.parent.Find("Btn_Sure").GetComponent<Button>();
ReferencePoint = transform.Find("ReferencePoint");
Content = transform.Find("Viewport/Content");
Btn_Left.onClick.AddListener(InputLeft);
Btn_Right.onClick.AddListener(InputRight);
}
public void InputLeft()
{
print("Left");
Indexer--;
}
public void InputRight()
{
print("Right");
Indexer++;
}
}
脚本挂在Scroll View 上
其它节点如下图
运行效果
//版本二:加了几行,控制左右按钮显示和隐藏
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class SelectTarget : MonoBehaviour
{
public Button Btn_Left;
public Button Btn_Right;
public Transform ReferencePoint;//参考位置(显示区域中央)
public Transform Content;//被移动物体
private int index;
public int Indexer
{
get
{
return index;
}
set
{
if (value < 0)
{
index = 0;
}
else if (value > Content.transform.childCount - 1)
{
index = Content.transform.childCount - 1;
}
else
{
index = value;
float A = Content.GetChild(index).position.x - ReferencePoint.position.x;
Content.DOMoveX(Content.position.x - A, 1f);
}
if (index == 0)
{
print(" //最左");
Btn_Left.gameObject.SetActive(false);
}
else
Btn_Left.gameObject.SetActive(true);
if (index == Content.childCount-1)
{
print(" //最右");
Btn_Right.gameObject.SetActive(false);
}
else
Btn_Right.gameObject.SetActive(true);
}
}
public void Awake()
{
Btn_Left = transform.Find("Btn_Left").GetComponent<Button>();
Btn_Right = transform.Find("Btn_Right").GetComponent<Button>();
ReferencePoint = transform.Find("ReferencePoint");
Content = transform.Find("Viewport/Content");
Btn_Left.onClick.AddListener(InputLeft);
Btn_Right.onClick.AddListener(InputRight);
}
private void OnEnable()
{
ResetList();
}
public void ResetList()
{
index = 0;
float A = Content.GetChild(0).position.x - ReferencePoint.position.x;//差值;
Content.DOMoveX(Content.position.x - A, 0);
Btn_Left.gameObject.SetActive(false);
}
public void InputLeft()
{
print("Left");
Indexer--;
}
public void InputRight()
{
print("Right");
Indexer++;
}
}