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

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).


Solution 1:[1]

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);
        }

Solution 2:[2]

Well, better late than never. I have the same problem in my old Unity 5.6x. So, I found that switching between movementType causes scrollrect to update if you wait for few frames. Use:

StartCoroutine(UpdateScrollRect());
IEnumerator UpdateScrollRect()
    {
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        ScrolRect.movementType = ScrollRect.MovementType.Elastic;
        ScrolRect.elasticity = 0f;
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        ScrolRect.movementType = ScrollRect.MovementType.Clamped;
    }

Try also to play with number of frames skip, so it fits your situation. Cheers! -Pavel

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex
Solution 2 user18896309