Unity UI ScrollRect jumping fix

This post was copied from my old Medium account

For a while I’ve been experiencing, and ignoring, a problem in my UI where after removing an item from a layout the scrollview would jump to the top.

I can't believe I lived like this

It was confusing because for a while I assumed it was a bug in my own scrolling logic, but after debugging it turned out none of my scrolling values were changing, just the internal bounds rect of the Unity ScrollRect.

The solution ended up being simple: after destroying or deactivating the GameObject from the UI layout, make sure to reset the ScrollRect scroll position back to what it was before the change, like below.

// Assume _desiredScroll was set to _scrollRect.normalizedPosition previously
Canvas.ForceUpdateCanvases();
_scrollRect.normalizedPosition = _desiredScroll;

Either the ScrollRect is hardcoded to reset its position when child layout changes, or the layout has a single frame of incorrect size or something after a change, but this seems to fix the problem!