気ままなUnityエンジニアブログ

新米Unityエンジニアが送る解説アウトプットブログです。Twitter : @UjinUnity

MENU

【Unity】Dotweenでスクロール機能を作ろう!

スポンサーリンク

f:id:Wojtek:20190909113609g:plain

DoTweenとScrollRectを作って簡単なスクロール機能を作ってみましょう!

ScrollViewの設定

f:id:Wojtek:20190909113738p:plain

UI -> ScrollViewをUnity上に設定してください。

AutoScrollの作成

f:id:Wojtek:20190909114004p:plain

今回使用するAutoScroll .csをScrollViewにアタッチしてください。
その際に、デフォルトで設定されているScrollViewは取り外してください。

AutoScrollのソースコードはこのようになっております。

using System.Collections;

using System.Collections.Generic;

using DG.Tweening;

using UnityEngine;

using UnityEngine.UI;

 

public class AutoScroll : ScrollRect {

 

    private float m_Timer;

    private float m_SlideWitdh;

    protected override void Start () {

 

        GridLayoutGroup grid = this.content.GetComponent<GridLayoutGroup> ();

 

        this.m_SlideWitdh = grid.cellSize.x + grid.spacing.x;

 

    }

 

    protected override void LateUpdate () {

        base.LateUpdate ();

 

        this.m_Timer += Time.deltaTime;

 

        if (this.m_Timer >= 3f) {

            this.m_Timer = 0;

 

            this.autoSlide ();

        }

    }

 

    private void autoSlide () {

 

        this.content.DOAnchorPosX (this.m_SlideWitdh, 1f)

            .SetEase (Ease.Linear)

            .OnComplete (() => {

                // 位置を初期化

                this.content.anchoredPosition = Vector2.zero;

            });

    }

}

上記を実行すると最初にみたgifのような動きになります。

あとは表示する画像を切り替えたり、改造して自動スクロールにしてみてください!