Unity实现广告滚动播放、循环播放、鼠标切换的效果

 效果:

 场景结构:

Unity实现广告滚动播放、循环播放、鼠标切换的效果_第1张图片

特殊物体:panel下面用排列组件horizent layout group放置多个需要显示的面板,用mask遮罩好。

Unity实现广告滚动播放、循环播放、鼠标切换的效果_第2张图片

 

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 update
    void Start()
    {
        rollPanel = transform.Find("Mask/RollPanel").GetComponent();
        toggleGroup = transform.Find("TogglePanel/ToggleGroup").GetComponent();
        toggles = transform.GetComponentsInChildren();

        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);
            }));
            
        }
    }
}

你可能感兴趣的:(unity,游戏引擎)