0
\$\begingroup\$

I've got a Scrollbar with a dynamically generated number of entries, and I'm trying to figure out how to get it to act so that there's a lead-in of the first 3 items (example number based on the size of my scroll area) where the area won't move. This then leaves the current selected item as the one in the centre of the area, and the content should move up so that the selection remains in the centre until the last 3 are visible, when the selection continues down to the bottom.

My efforts so far have varied from calculate the percentage through the content (currentSelected / numItems) & assign the scrollbar.value, to putting that percentage through an AnimationCurve, which gives me the "dead zones" at the beginning & end, but introduces unpleasant skipping & doesn't centre the selected item.

Also, this is intended to be for navigating through discrete objects using a gamepad.

\$\endgroup\$
0
\$\begingroup\$

Really depends on how your scrolling is setup. Do you know the height of each entry? If you do then you can loop through the child count and offset the height for each entry until you hit your selected target.

public ScrollRect ScrollerRect;
public RectTransform SelectedEntry;

void Start()
{
    //test the selected entry - remove and add your own selection method.
    if (SelectedEntry != null)
        ScrollToEntryView();//--pass in selected entry and scroll to view
}
void ScrollToEntryView()
{
    float scrollToPos = 0;
    float yMax = ScrollerRect.content.rect.yMax;
    float entryHeight = 150;
    for (int i = 0; i < ScrollerRect.content.childCount; i++)
    {
        if (SelectedEntry.gameObject.name == ScrollerRect.content.GetChild(i).gameObject.name)
            SetScrollContentPoint(scrollToPos);
        else
            scrollToPos = yMax += entryHeight;
    }
}
void SetScrollContentPoint(float yPos)
{
    ScrollerRect.content.offsetMax = new Vector2(0, yPos);
    EventSystem.current.SetSelectedGameObject(SelectedEntry.gameObject, null);
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.