Search Unity

Setting ScrollRect normalizedPosition immediately after adding content

Discussion in 'UGUI & TextMesh Pro' started by arvzg, Jul 29, 2019.

  1. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    619
    Hello

    I'm having a peculiar issue with setting ScrollRect normalizedPosition. In general cases, if I'm just setting normalizedPosition and nothing else, it works perfectly fine, but I have a situation where I have 2 'tabs', when clicking on a tab, the contents of the ScrollRect are destroyed, and different items are loaded. I want to remember the ScrollRect's normalizedPosition for each tab, and re-set them when going back and forth between tabs

    So in pseudocode, the logic is like this:

    Code (CSharp):
    1. void PressTabOneButton()
    2. {
    3.    DestroyAllContents();
    4.    LoadUpNewContents();
    5.    scrollRect.horizontalNormalizedPosition = 0.5f; //Just as a test value
    6. }
    What should happen there is when I switch tabs, the ScrollRect should be set to the middle but what is actually happening is the normalizedValue ends up being some other value.

    Looks like by the time I get to setting the normalizedPosition, the Scroll Rect isn't quite 'ready' yet, so it sets the position to 0.5f for 1 frame, and then in the next frame it 'jumps' to some other value.

    I think what's happening is the layouts haven't fully rebuilt yet by this time, perhaps it only finishes rebuilding everything by the next frame? So I turned this into a Coroutine and waited 1 frame before setting the normalizedPosition. 1 frame doesn't work, but strangely enough waiting 2 frames does work!

    I really don't think having to wait 2 frames is ideal, so I was wondering if there's some other way to make this work properly all in the same frame? I have tried ALL SORTS of possible things just before setting the normalizedPosition, including:

    • Canvas.ForceUpdateCanvases()
    • CalculateLayoutInputVertical()
      and
      SetLayoutHorizontal()
    • set enabled = false and back to true again
    • LayoutRebuilder.ForceRebuildLayoutImmediate()
    All these result in the normalizedPosition to jump to strange values I don't understand.

    How can I make this work in the same frame right after adding content to the ScrollRect?
     
    Igorexa and gaolei_nls like this.
  2. Nodrap

    Nodrap

    Joined:
    Nov 4, 2011
    Posts:
    83
    Yep, hit this exact same annoying problem. So hard to work with.