Scroll rect with a slider - how to turn slider on and off depending if content is large enough to need scrolling

Hi,

I’m using a scroll rect with a slider instead of a scrollbar, as I want the handle to stay a fixed size.

When using the scrollbar, it automatically turns off when the content fits within the scrollview, and turns on when the content does not and needs to be scrolled in order to view all of it.

How do I achieve this same behaviour with a slider. Do I check the H Delta for the Content Rect Transform. Or is there an event I can listen out for? Unsure how it’s being achieved with the scrollbar.

Thanks,
Laurien

Hi @laurienash ,
sorry its a bit late but this is what you can do.


  • For horizontal detection

return m_ContentBounds.size.x > m_ViewBounds.size.x + 0.01f;


  • For verticle detection

return m_ContentBounds.size.x > m_ViewBounds.size.x + 0.01f;


Following image will also help


Although there is a little issue here. In Start() function, we cannot get actual bounds as they are updated a little late, so we have to use invoke. You can use my code

public class ScrollRectSlider : MonoBehaviour
{

    Slider slider;
    Bounds cBounds;
    Bounds vBounds;
    public ScrollRect scrollRect;

    void Start()
    {
        slider = GetComponent<Slider>();
        Invoke("VerticalAutoHide", 0.01f);
    }

    public void SetScrollBarHandleSize(float size)
    {
        scrollRect.horizontalNormalizedPosition = slider.value;
    }

    public void VerticalAutoHide()
    {
        // print("VerticalAutoHide");
        cBounds = new Bounds(scrollRect.content.rect.center, scrollRect.content.rect.size);
        vBounds = new Bounds(scrollRect.viewport.rect.center, scrollRect.viewport.rect.size);

        print($"cBounds.size.x = {cBounds.size.x} and vBounds.size.x = {vBounds.size.x}");
        if (cBounds.size.x > vBounds.size.x + 0.01f)
        {
            //show slider
            print("show");
            this.gameObject.SetActive(true);
        }
        else
        {
            //hide slider
            print("hide");
            this.gameObject.SetActive(false);
        }
    }
}