Search Unity

Scrollbar Toggle Script has delay on reading RectTransform.rect.height

Discussion in 'UGUI & TextMesh Pro' started by Armageddon104, Aug 10, 2015.

  1. Armageddon104

    Armageddon104

    Joined:
    Sep 14, 2014
    Posts:
    23
    Hey there. So I have a ScrollRect that's content is dynamic. I wrote this little script for the Scrollbar so that when the ScrollRect content becomes longer than the parent panel it'll toggle the Scrollbar on.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ScrollbarEnabler : MonoBehaviour {
    6.  
    7.     public RectTransform ScrollRectHolder;
    8.     public RectTransform ScrollList;
    9.  
    10.     public void CheckHeights() {
    11.         if (ScrollList.rect.height > ScrollRectHolder.rect.height) {
    12.             this.gameObject.SetActive(true);
    13.             //Debug.Log("It is larger");
    14.             //this.enabled = true;
    15.         }
    16.         else {
    17.             this.gameObject.SetActive(false);
    18.             //Debug.Log("It is smaller");
    19.             //this.enabled = false;
    20.         }
    21.         //print ("List " + ScrollList.rect.height);
    22.         //print ("Holder " + ScrollRectHolder.rect.height);
    23.     }
    24. }
    25.  
    Then I call it from this function in a script controlling my ScrollRects:

    Code (csharp):
    1.  
    2. public void DisplayItem(string gottenItemName, string gottenItemDescription) {
    3.         itemNameHeaderText.text = gottenItemName;
    4.         itemDescriptionText.text = gottenItemDescription;
    5.         //itemDescriptionText.text.Replace("\n", );
    6.         scrollbarEnabler2.CheckHeights();
    7.         Scrollbar scrollBar2 = scrollbarEnabler2.GetComponent<Scrollbar>();
    8.         scrollBar2.value = 1;
    9. }
    10.  
    You'd think since I'm setting the text first, the text's panel has a content size fitter so that it stretches when the text is longer. And that panel is then attached to the ScrollRect's content. So since I'm setting the text first, the panel resizes, and then I call CheckHeights(). But it only works the second time I click it. So I think the Rect's height is updating way later for some reason.
    The print statements in the first script always print out the wrong numbers the first time I click, and then it reads them properly the second time.
    So if I click on a button that has a long description and it fires DisplayItem() the Scrollbar doesn't enable, if I click on another button that fires DisplayItem() but the description is short it'll display the Scrollbar from the previous click, because it's not reading the Rect's height until the second time and I have no idea why.

    I hope I explained that all well, this is a very frustrating bug.