S: AutoScrollRect, Make your Scroll Rect Auto Scroll Content

With the declared Properties we Start a PingPong Mathf that will increment and decrement the Scroll Rect Content between the value 0 and 1 and perform the Auto Scroll.

Attach the Script to a GameObject and Drag the Scroll View inside the Scroll Rect Property in the Unity Inspector. Set the Scroll Duration Time and it is Ready to go!

AutoScrollRect.cs

				
					using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class AutoScrollRect : MonoBehaviour
{
    //Assign the Scroll Rect inside the Unity Inspector 
    [SerializeField] ScrollRect scrollRect;
    [SerializeField] float scrollDuration = 5.0f;

    void OnEnable()
    {
        StartCoroutine(AutoScroll());
    }

    IEnumerator AutoScroll()
    {
        var t = 0.0f;
        while (true)
        {
            t += Time.deltaTime / scrollDuration;
            scrollRect.verticalNormalizedPosition = 1 - Mathf.PingPong(t, 1);
            yield return null;
        }
    }

    void OnDisable()
    {
        StopAllCoroutines();
    }
}
				
			

With the declared Properties we Start a PingPong Mathf that will increment and decrement the Scroll Rect Content between the value 0 and 1 and perform the Auto Scroll.

Attached to a GameObject you can Assign a Scroll Rect inside the Unity Inspector to the AutoScrollRect. Set the Duration Time it takes the Scroller to go from Top to Bottom, or Bottom to Top. The ScrollRect will continue to Scroll until the Object or AutoScrollRect Script gets disabled.

Happy Development <3

Leave a Reply

Your email address will not be published.