设置空物体的大小,要知足包括的内容。提供一个小的技巧,能够将建立出来的关卡选择按钮放在一个空的游戏物体下面,数组
这样改按钮就不会被Grid进行缩放了。将按钮添加到挂载GridLayoutGroup组件的游戏物体下面,成为其子物体。this
其中的Show Mask Graphic决定是否显示该背景色,通常是不显示的,则取消勾选。其中Image的大小就是能够显示内容的大小,也就是能够进行滑动的大小。spa
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; //事件接口的命名空间 using UnityEngine.UI; public class MyScrollRect : MonoBehaviour,IBeginDragHandler,IEndDragHandler { public float smoothing = 4.0f; //拖拽的速度 public Toggle[] ToggleArray; //设置toggle数组,和RectArray数组下标对应 private ScrollRect scrollRect; private float[] RectArray =new float[] { 0f, 0.333333f, 0.666666f, 1f }; //一共是4页,其中每一页的位置信息 private float horizontalPositionTarget = 0; //目标的拖拽位置 private bool isDrag = false; //经过设定标志位来肯定是不是在拖拽,若是在拖拽就不进行移动 private void Start() { scrollRect = this.GetComponent<ScrollRect>(); //须要经过ScrollRect组件对其进行获取位置信息 } private void Update() { if (isDrag==false) { scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, horizontalPositionTarget, Time.deltaTime * smoothing); //进行插值运算 } } /// <summary> /// 拖拽开始的事件 /// </summary> /// <param name="eventData"></param> public void OnBeginDrag(PointerEventData eventData) { isDrag = true; //拖拽开始,进行中 } /// <summary> /// 拖拽结束的事件 /// </summary> /// <param name="eventData"></param> public void OnEndDrag(PointerEventData eventData) { isDrag = false; //拖拽结束 float Pos_x = scrollRect.horizontalNormalizedPosition; int index = 0; //默认是从第一页开始的 float offset = Mathf.Abs(Pos_x - RectArray[index]); //经过查找最小偏移量来肯定是在那一页 for (int i = 1; i < RectArray.Length; i++) { //经过遍历找出离页数最近的哪个 float offset_temp = Mathf.Abs(Pos_x - RectArray[i]); if(offset_temp < offset) { //当有比第一页还近的就要进行更换了 index = i; offset = offset_temp; } } horizontalPositionTarget = RectArray[index]; //经过设定目标值而后经过lerp来进行插值运算便可 ToggleArray[index].isOn = true; //当经过滚动页面的时候也要对下面的按钮进行同步 //scrollRect.horizontalNormalizedPosition = RectArray[index]; //不太好,没有平滑的效果 } //如下四个是经过注册按钮的点击事件;来达到换页的效果的 public void MoveToPad_01(bool isOn) { //第一页的按钮 if (isOn==true) { //当选中了就会进行移动: horizontalPositionTarget = RectArray[0]; //经过设定目标值而后经过lerp来进行插值运算便可 } } public void MoveToPad_02(bool isOn) { //第二页的按钮 if (isOn == true) { //当选中了就会进行移动: horizontalPositionTarget = RectArray[1]; //经过设定目标值而后经过lerp来进行插值运算便可 } } public void MoveToPad_03(bool isOn) { //第三页的按钮 if (isOn == true) { //当选中了就会进行移动: horizontalPositionTarget = RectArray[2]; //经过设定目标值而后经过lerp来进行插值运算便可 } } public void MoveToPad_04(bool isOn) { //第四页的按钮 if (isOn == true) { //当选中了就会进行移动: horizontalPositionTarget = RectArray[3]; //经过设定目标值而后经过lerp来进行插值运算便可 } } }