using UnityEngine; using UnityEngine.UI; using System; using System.Collections; public enum LocatePos { Left, Right, Center, Up, Down, Middle, } public static class ExtensionScrollRect { public static MoveRoot Locate(this ScrollRect scrollRect, int index, float duration, Curve curve, LocatePos locatePos) { float scaleFactor = scrollRect.GetComponent().canvas.scaleFactor; LayoutGroup layoutGroup = scrollRect.content.GetComponent(); RectTransform tra1 = scrollRect.GetComponent(); Rect rect1 = tra1.rect; RectTransform tra2 = scrollRect.content.GetChild(index).GetComponent(); Rect rect2 = tra2.rect; if (locatePos == LocatePos.Up) { Vector3 itemPos = tra2.position + new Vector3(0, rect2.yMax, 0) * scaleFactor; Vector3 targetPos = tra1.position + new Vector3(0, rect1.yMax - layoutGroup.padding.top, 0) * scaleFactor; Vector3 offset = targetPos - itemPos; offset.x = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } if (locatePos == LocatePos.Down) { Vector3 itemPos = tra2.position + new Vector3(0, rect2.yMin, 0) * scaleFactor; Vector3 targetPos = tra1.position + new Vector3(0, rect1.yMin + layoutGroup.padding.bottom, 0) * scaleFactor; Vector3 offset = targetPos - itemPos; offset.x = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } else if (locatePos == LocatePos.Middle) { Vector3 itemPos = tra2.position + new Vector3(rect2.center.x, rect2.center.y, 0); Vector3 targetPos = tra1.position + new Vector3(rect1.center.x, rect1.center.y, 0); Vector3 offset = targetPos - itemPos; offset.x = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } if (locatePos == LocatePos.Left) { Vector3 itemPos = tra2.position + new Vector3(rect2.xMin, 0, 0) * scaleFactor; Vector3 targetPos = tra1.position + new Vector3(rect1.xMin + layoutGroup.padding.left, 0, 0) * scaleFactor; Vector3 offset = targetPos - itemPos; offset.y = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } if (locatePos == LocatePos.Right) { Vector3 itemPos = tra2.position + new Vector3(rect2.xMax, 0, 0) * scaleFactor; Vector3 targetPos = tra1.position + new Vector3(rect1.xMax - layoutGroup.padding.right, 0, 0) * scaleFactor; Vector3 offset = targetPos - itemPos; offset.y = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } if (locatePos == LocatePos.Center) { Vector3 itemPos = tra2.position + new Vector3(rect2.center.x, rect2.center.y, 0); Vector3 targetPos = tra1.position + new Vector3(rect1.center.x, rect1.center.y, 0); Vector3 offset = targetPos - itemPos; offset.y = 0; return scrollRect.content.MoveOffset2D(offset, duration, false, curve); } throw new Exception(); } public static MoveRoot Locate(this ScrollRect scrollRect, Transform item, float duration, Curve curve, LocatePos locatePos) { return scrollRect.Locate(item.GetSiblingIndex(), duration, curve, locatePos); } }