效果:
场景结构:
特殊物体:panel下面用排列组件horizent layout group放置多个需要显示的面板,用mask遮罩好。
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;public class RollControlPanel : MonoBehaviour
{private RectTransform rollPanel;private Vector2 startPos;private ToggleGroup toggleGroup;private Toggle[] toggles;private int curToggleIndex = 0;private int toggleCount;public float moveValue = 756;// Start is called before the first frame updatevoid Start(){rollPanel = transform.Find("Mask/RollPanel").GetComponent<RectTransform>();toggleGroup = transform.Find("TogglePanel/ToggleGroup").GetComponent<ToggleGroup>();toggles = transform.GetComponentsInChildren<Toggle>();startPos = rollPanel.anchoredPosition;toggleCount = toggles.Length;for (int i = 0; i < toggleCount; i++){Toggle toggle = toggles[i];toggles[i].onValueChanged.AddListener((arg0 =>{OnToggleOpen(toggle);}));}IEnumerator enumerator = SetToggle();Coroutine setTogglesetToggle= StartCoroutine(enumerator);}//定时设置哪个toggle打开IEnumerator SetToggle(){while (true){yield return new WaitForSeconds(1f);Debug.Log("切换toggle");if (curToggleIndex < toggleCount-1){curToggleIndex++;toggles[curToggleIndex].isOn = true;}else{curToggleIndex = 0;toggles[curToggleIndex].isOn = true;}}}//只需要关注移动到toggleIndex对应的本地绝对位置void OnToggleOpen(Toggle toggle){if (toggle.isOn){//获取属于第几个toggle,指定panel移动到某个位置,停止协程重置时间for (int i = 0; i < toggleCount; i++){if (toggle==toggles[i]){curToggleIndex = i;break;}}float curPosX = startPos.x - curToggleIndex * moveValue;StopAllCoroutines();rollPanel.DOAnchorPosX(curPosX, 0.5f).OnComplete((() =>{//每次动结束,重新开一次协程IEnumerator enumerator = SetToggle();Coroutine setTogglesetToggle= StartCoroutine(enumerator);}));}}
}