Last active
October 1, 2019 06:26
-
-
Save GeorgiyRyaposov/770608b98531a907e61813c2f5f202d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
namespace Prototype.Scripts.Utils | |
{ | |
public static class ScrollRectExtension | |
{ | |
public static void SnapToChild(this ScrollRect scrollRect, RectTransform child) | |
{ | |
scrollRect.content.localPosition = GetContentLocalPositionForChild(scrollRect, child); | |
} | |
public static void SnapToChildLocalPosition(this ScrollRect scrollRect, Vector2 childLocalPosition) | |
{ | |
scrollRect.content.localPosition = GetContentLocalPositionForChild(scrollRect, childLocalPosition); | |
} | |
/// <summary> | |
/// Get position, which will bring to center child element | |
/// </summary> | |
/// <param name="scrollRect"></param> | |
/// <param name="child"></param> | |
/// <returns></returns> | |
public static Vector2 GetContentLocalPositionForChild(this ScrollRect scrollRect, RectTransform child) | |
{ | |
return GetContentLocalPositionForChild(scrollRect, child.localPosition); | |
} | |
public static Vector2 GetContentLocalPositionForChild(this ScrollRect scrollRect, Vector2 childLocalPosition) | |
{ | |
Canvas.ForceUpdateCanvases(); | |
Vector2 viewportLocalPosition = scrollRect.viewport.localPosition; | |
Vector2 result = new Vector2( | |
0 - (viewportLocalPosition.x + childLocalPosition.x), | |
0 - (viewportLocalPosition.y + childLocalPosition.y)); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment