Skip to content

Instantly share code, notes, and snippets.

@marcelschmidtdev
Created March 30, 2016 00:42
Show Gist options
  • Save marcelschmidtdev/14a1528f98307d3d826f522196e9817f to your computer and use it in GitHub Desktop.
Save marcelschmidtdev/14a1528f98307d3d826f522196e9817f to your computer and use it in GitHub Desktop.
Autoscroll Scrollrect for Unity
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[RequireComponent(typeof(ScrollRect))]
public class ScrollToSelected : MonoBehaviour
{
public float scrollSpeed = 10f;
ScrollRect m_ScrollRect;
RectTransform m_RectTransform;
RectTransform m_ContentRectTransform;
RectTransform m_SelectedRectTransform;
void Awake()
{
m_ScrollRect = GetComponent<ScrollRect>();
m_RectTransform = GetComponent<RectTransform>();
m_ContentRectTransform = m_ScrollRect.content;
}
void Update()
{
UpdateScrollToSelected();
}
void UpdateScrollToSelected()
{
// grab the current selected from the eventsystem
GameObject selected = EventSystem.current.currentSelectedGameObject;
if (selected == null)
{
return;
}
if (selected.transform.parent != m_ContentRectTransform.transform)
{
return;
}
m_SelectedRectTransform = selected.GetComponent<RectTransform>();
// math stuff
Vector3 selectedDifference = m_RectTransform.localPosition - m_SelectedRectTransform.localPosition;
float contentHeightDifference = (m_ContentRectTransform.rect.height - m_RectTransform.rect.height);
float selectedPosition = (m_ContentRectTransform.rect.height - selectedDifference.y);
float currentScrollRectPosition = m_ScrollRect.normalizedPosition.y * contentHeightDifference;
float above = currentScrollRectPosition - (m_SelectedRectTransform.rect.height / 2) + m_RectTransform.rect.height;
float below = currentScrollRectPosition + (m_SelectedRectTransform.rect.height / 2);
// check if selected is out of bounds
if (selectedPosition > above)
{
float step = selectedPosition - above;
float newY = currentScrollRectPosition + step;
float newNormalizedY = newY / contentHeightDifference;
m_ScrollRect.normalizedPosition = Vector2.Lerp(m_ScrollRect.normalizedPosition, new Vector2(0, newNormalizedY), scrollSpeed * Time.deltaTime);
}
else if (selectedPosition < below)
{
float step = selectedPosition - below;
float newY = currentScrollRectPosition + step;
float newNormalizedY = newY / contentHeightDifference;
m_ScrollRect.normalizedPosition = Vector2.Lerp(m_ScrollRect.normalizedPosition, new Vector2(0, newNormalizedY), scrollSpeed * Time.deltaTime);
}
}
}
@ribeirosamuel96
Copy link

You saved me!

@nakassaur
Copy link

The only correct way to do this which is using the Event System Navigation. Thanks for saving me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment