ScrollRect does not correctly update the position when clamping the normalized position, after removing/deactivating a child element from the content

Alex picture Alex · Mar 24, 2016 · Viewed 8.2k times · Source

This is an issue that I had to resolve myself after finding no solutions for it.

The issue was that after removing a GameObject element from the ScrollRect's content, it would not clamp its normalized position until the user starts moving it again. This could lead to the ScrollRect showing empty space when it is showing the last elements and has deactivated the last element from the parent.

  • The normalized position value was not updating until the user interacted with the ScrollRect content.
  • Setting the normalized position manually, after deactivating an element, would not work as it was working on old values that have not been updated yet (see above for why).

Answer

Alex picture Alex · Mar 24, 2016

The best solution I have found is to

  1. Force a Canvas update after detecting a child, in the ScrollRect's content, being removed.
  2. Then Clamping the value, since the normalized position has been updated correctly.

Example code:

        if (isRemoving) {
            Canvas.ForceUpdateCanvases();
            scrollRect.horizontalNormalizedPosition = Mathf.Clamp(scrollRect.horizontalNormalizedPosition, 0f, 1f);
        }