Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

scroll list - scroll image and text at the same time

Discussion in 'Scripting' started by Deleted User, Sep 19, 2018.

  1. Deleted User

    Deleted User

    Guest

    hi
    i use the following class for scrolling back and forth. i have left and right buttons for this purpose.
    however , now by scrolling , just one ui image is changing .
    how i add for each image a ui text too..
    any help is appreciated.
    thanks.
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4. using System.Collections;
    5. using System.Collections.Generic;
    6.  
    7. [RequireComponent(typeof(Image))]
    8. [RequireComponent(typeof(Mask))]
    9. [RequireComponent(typeof(ScrollRect))]
    10. public class GameHelpScroller : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
    11. {
    12.  
    13.     [Tooltip("Set starting page index - starting from 0")]
    14.     public int startingPage = 0;
    15.     [Tooltip("Threshold time for fast swipe in seconds")]
    16.     public float fastSwipeThresholdTime = 0.3f;
    17.     [Tooltip("Threshold time for fast swipe in (unscaled) pixels")]
    18.     public int fastSwipeThresholdDistance = 100;
    19.     [Tooltip("How fast will page lerp to target position")]
    20.     public float decelerationRate = 10f;
    21.     [Tooltip("Button to go to the previous page (optional)")]
    22.     public GameObject prevButton;
    23.     [Tooltip("Button to go to the next page (optional)")]
    24.     public GameObject nextButton;
    25.     [Tooltip("Sprite for unselected page (optional)")]
    26.     public Sprite unselectedPage;
    27.     [Tooltip("Sprite for selected page (optional)")]
    28.     public Sprite selectedPage;
    29.     [Tooltip("Container with page images (optional)")]
    30.     public Transform pageSelectionIcons;
    31.  
    32.     // fast swipes should be fast and short. If too long, then it is not fast swipe
    33.     private int _fastSwipeThresholdMaxLimit;
    34.  
    35.     private ScrollRect _scrollRectComponent;
    36.     private RectTransform _scrollRectRect;
    37.     private RectTransform _container;
    38.  
    39.     private bool _horizontal;
    40.  
    41.     // number of pages in container
    42.     private int _pageCount;
    43.     private int _currentPage;
    44.  
    45.     // whether lerping is in progress and target lerp position
    46.     private bool _lerp;
    47.     private Vector2 _lerpTo;
    48.  
    49.     // target position of every page
    50.     private List<Vector2> _pagePositions = new List<Vector2>();
    51.  
    52.     // in draggging, when dragging started and where it started
    53.     private bool _dragging;
    54.     private float _timeStamp;
    55.     private Vector2 _startPosition;
    56.  
    57.     // for showing small page icons
    58.     private bool _showPageSelection;
    59.     private int _previousPageSelectionIndex;
    60.     // container with Image components - one Image for each page
    61.     private List<Image> _pageSelectionImages;
    62.  
    63.     //------------------------------------------------------------------------
    64.     void Start()
    65.     {
    66.         _scrollRectComponent = GetComponent<ScrollRect>();
    67.         _scrollRectRect = GetComponent<RectTransform>();
    68.         _container = _scrollRectComponent.content;
    69.         _pageCount = _container.childCount;
    70.  
    71.         // is it horizontal or vertical scrollrect
    72.         if (_scrollRectComponent.horizontal && !_scrollRectComponent.vertical) {
    73.             _horizontal = true;
    74.         } else if (!_scrollRectComponent.horizontal && _scrollRectComponent.vertical) {
    75.             _horizontal = false;
    76.         } else {
    77.             Debug.LogWarning("Confusing setting of horizontal/vertical direction. Default set to horizontal.");
    78.             _horizontal = true;
    79.         }
    80.  
    81.         _lerp = false;
    82.  
    83.         // init
    84.         SetPagePositions();
    85.         SetPage(startingPage);
    86.         InitPageSelection();
    87.         SetPageSelection(startingPage);
    88.  
    89.         // prev and next buttons
    90.         if (nextButton)
    91.             nextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); });
    92.  
    93.         if (prevButton)
    94.             prevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); });
    95.     }
    96.  
    97.     //------------------------------------------------------------------------
    98.     void Update()
    99.     {
    100.         // if moving to target position
    101.         if (_lerp) {
    102.             // prevent overshooting with values greater than 1
    103.             float decelerate = Mathf.Min(decelerationRate * Time.deltaTime, 1f);
    104.             _container.anchoredPosition = Vector2.Lerp(_container.anchoredPosition, _lerpTo, decelerate);
    105.             // time to stop lerping?
    106.             if (Vector2.SqrMagnitude(_container.anchoredPosition - _lerpTo) < 0.25f) {
    107.                 // snap to target and stop lerping
    108.                 _container.anchoredPosition = _lerpTo;
    109.                 _lerp = false;
    110.                 // clear also any scrollrect move that may interfere with our lerping
    111.                 _scrollRectComponent.velocity = Vector2.zero;
    112.             }
    113.  
    114.             // switches selection icon exactly to correct page
    115.             if (_showPageSelection) {
    116.                 SetPageSelection(GetNearestPage());
    117.             }
    118.         }
    119.     }
    120.  
    121.     //------------------------------------------------------------------------
    122.     private void SetPagePositions()
    123.     {
    124.         int width = 0;
    125.         int height = 0;
    126.         int offsetX = 0;
    127.         int offsetY = 0;
    128.         int containerWidth = 0;
    129.         int containerHeight = 0;
    130.  
    131.         if (_horizontal) {
    132.             // screen width in pixels of scrollrect window
    133.             width = (int)_scrollRectRect.rect.width;
    134.             // center position of all pages
    135.             offsetX = width / 2;
    136.             // total width
    137.             containerWidth = width * _pageCount;
    138.             // limit fast swipe length - beyond this length it is fast swipe no more
    139.             _fastSwipeThresholdMaxLimit = width;
    140.         } else {
    141.             height = (int)_scrollRectRect.rect.height;
    142.             offsetY = height / 2;
    143.             containerHeight = height * _pageCount;
    144.             _fastSwipeThresholdMaxLimit = height;
    145.         }
    146.  
    147.         // set width of container
    148.         Vector2 newSize = new Vector2(containerWidth, containerHeight);
    149.         _container.sizeDelta = newSize;
    150.         Vector2 newPosition = new Vector2(containerWidth / 2, containerHeight / 2);
    151.         _container.anchoredPosition = newPosition;
    152.  
    153.         // delete any previous settings
    154.         _pagePositions.Clear();
    155.  
    156.         // iterate through all container childern and set their positions
    157.         for (int i = 0; i < _pageCount; i++) {
    158.             RectTransform child = _container.GetChild(i).GetComponent<RectTransform>();
    159.             Vector2 childPosition;
    160.             if (_horizontal) {
    161.                 childPosition = new Vector2(i * width - containerWidth / 2 + offsetX, 0f);
    162.             } else {
    163.                 childPosition = new Vector2(0f, -(i * height - containerHeight / 2 + offsetY));
    164.             }
    165.             child.anchoredPosition = childPosition;
    166.             _pagePositions.Add(-childPosition);
    167.         }
    168.     }
    169.  
    170.     //------------------------------------------------------------------------
    171.     private void SetPage(int aPageIndex)
    172.     {
    173.         aPageIndex = Mathf.Clamp(aPageIndex, 0, _pageCount - 1);
    174.         _container.anchoredPosition = _pagePositions[aPageIndex];
    175.         _currentPage = aPageIndex;
    176.     }
    177.  
    178.     //------------------------------------------------------------------------
    179.     private void LerpToPage(int aPageIndex)
    180.     {
    181.         aPageIndex = Mathf.Clamp(aPageIndex, 0, _pageCount - 1);
    182.         _lerpTo = _pagePositions[aPageIndex];
    183.         _lerp = true;
    184.         _currentPage = aPageIndex;
    185.     }
    186.  
    187.     //------------------------------------------------------------------------
    188.     private void InitPageSelection()
    189.     {
    190.         // page selection - only if defined sprites for selection icons
    191.         _showPageSelection = unselectedPage != null && selectedPage != null;
    192.         if (_showPageSelection) {
    193.             // also container with selection images must be defined and must have exatly the same amount of items as pages container
    194.             if (pageSelectionIcons == null || pageSelectionIcons.childCount != _pageCount) {
    195.                 Debug.LogWarning("Different count of pages and selection icons - will not show page selection");
    196.                 _showPageSelection = false;
    197.             } else {
    198.                 _previousPageSelectionIndex = -1;
    199.                 _pageSelectionImages = new List<Image>();
    200.  
    201.                 // cache all Image components into list
    202.                 for (int i = 0; i < pageSelectionIcons.childCount; i++) {
    203.                     Image image = pageSelectionIcons.GetChild(i).GetComponent<Image>();
    204.                     if (image == null) {
    205.                         Debug.LogWarning("Page selection icon at position " + i + " is missing Image component");
    206.                     }
    207.                     _pageSelectionImages.Add(image);
    208.                 }
    209.             }
    210.         }
    211.     }
    212.  
    213.     //------------------------------------------------------------------------
    214.     private void SetPageSelection(int aPageIndex)
    215.     {
    216.         // nothing to change
    217.         if (_previousPageSelectionIndex == aPageIndex) {
    218.             return;
    219.         }
    220.  
    221.         // unselect old
    222.         if (_previousPageSelectionIndex >= 0) {
    223.             _pageSelectionImages[_previousPageSelectionIndex].sprite = unselectedPage;
    224.             _pageSelectionImages[_previousPageSelectionIndex].SetNativeSize();
    225.         }
    226.  
    227.         // select new
    228.         _pageSelectionImages[aPageIndex].sprite = selectedPage;
    229.         _pageSelectionImages[aPageIndex].SetNativeSize();
    230.  
    231.         _previousPageSelectionIndex = aPageIndex;
    232.     }
    233.  
    234.     //------------------------------------------------------------------------
    235.     private void NextScreen()
    236.     {
    237.         LerpToPage(_currentPage + 1);
    238.     }
    239.  
    240.     //------------------------------------------------------------------------
    241.     private void PreviousScreen() {
    242.         LerpToPage(_currentPage - 1);
    243.     }
    244.  
    245.     //------------------------------------------------------------------------
    246.     private int GetNearestPage() {
    247.         // based on distance from current position, find nearest page
    248.         Vector2 currentPosition = _container.anchoredPosition;
    249.  
    250.         float distance = float.MaxValue;
    251.         int nearestPage = _currentPage;
    252.  
    253.         for (int i = 0; i < _pagePositions.Count; i++) {
    254.             float testDist = Vector2.SqrMagnitude(currentPosition - _pagePositions[i]);
    255.             if (testDist < distance) {
    256.                 distance = testDist;
    257.                 nearestPage = i;
    258.             }
    259.         }
    260.  
    261.         return nearestPage;
    262.     }
    263.  
    264.     //------------------------------------------------------------------------
    265.     public void OnBeginDrag(PointerEventData aEventData) {
    266.         // if currently lerping, then stop it as user is draging
    267.         _lerp = false;
    268.         // not dragging yet
    269.         _dragging = false;
    270.     }
    271.  
    272.     //------------------------------------------------------------------------
    273.     public void OnEndDrag(PointerEventData aEventData) {
    274.         // how much was container's content dragged
    275.         float difference;
    276.         if (_horizontal) {
    277.             difference = _startPosition.x - _container.anchoredPosition.x;
    278.         } else {
    279.             difference = - (_startPosition.y - _container.anchoredPosition.y);
    280.         }
    281.  
    282.         // test for fast swipe - swipe that moves only +/-1 item
    283.         if (Time.unscaledTime - _timeStamp < fastSwipeThresholdTime &&
    284.             Mathf.Abs(difference) > fastSwipeThresholdDistance &&
    285.             Mathf.Abs(difference) < _fastSwipeThresholdMaxLimit) {
    286.             if (difference > 0) {
    287.                 NextScreen();
    288.             } else {
    289.                 PreviousScreen();
    290.             }
    291.         } else {
    292.             // if not fast time, look to which page we got to
    293.             LerpToPage(GetNearestPage());
    294.         }
    295.  
    296.         _dragging = false;
    297.     }
    298.  
    299.     //------------------------------------------------------------------------
    300.     public void OnDrag(PointerEventData aEventData) {
    301.         if (!_dragging) {
    302.             // dragging started
    303.             _dragging = true;
    304.             // save time - unscaled so pausing with Time.scale should not affect it
    305.             _timeStamp = Time.unscaledTime;
    306.             // save current position of cointainer
    307.             _startPosition = _container.anchoredPosition;
    308.         } else {
    309.             if (_showPageSelection) {
    310.                 SetPageSelection(GetNearestPage());
    311.             }
    312.         }
    313.     }
    314. }
    315.  
     
  2. shawnrevels

    shawnrevels

    Joined:
    Aug 13, 2014
    Posts:
    86
    Wow. Why don't you use unitys built in scroll rect . You wouldn't need to script all of this. And then you can just add the text to the content of the scroll rect along with images and what not.