728x90
아래 코드를 보기 전에 Scroll View에 content 안에 자식들의 위치값 계산을 편하게 하기 위해 Anchor Presets 좌상단에 피벗은 (0,1)으로 했습니다.
(이미지 참조)
* 코드에 사용된 DoTween은 코딩으로만 사용 가능한 버전은 Unity Asset Store에서 무료 버전으로 배포 중입니다.
// slot 은 Scroll View/Viewport/Content 안에 자식으로 붙인 개인들이 만든 Object를 인자로 받습니다.
public static bool ScrollFocus(RectTransform slot, float moveTime = 0.2f, Action act = null) // when the return true then not necessary moving
{
if (ReferenceEquals(slot, null))
{
if (act != null) act();
return true;
}
ScrollRect rect = slot.GetComponentInParent<ScrollRect>();
RectTransform scrollRoot = rect.transform as RectTransform;
RectTransform parent = slot.parent as RectTransform; // found transform must be contents in scroll view
Vector2 movePos = Vector2.zero;
if (rect.horizontal) // horizontal scroll able
{
if (slot.anchoredPosition.x + parent.anchoredPosition.x < 0)
movePos.x -= slot.anchoredPosition.x + parent.anchoredPosition.x;
else if (slot.anchoredPosition.x + slot.rect.width > parent.anchoredPosition.x * -1f + scrollRoot.rect.width)
movePos.y = (parent.anchoredPosition.x * -1f + scrollRoot.rect.width) - (slot.anchoredPosition.x + slot.rect.width);
}
if (rect.vertical) // vertical scroll able
{
if (slot.anchoredPosition.y + parent.anchoredPosition.y > 0)
movePos.y -= parent.anchoredPosition.y + slot.anchoredPosition.y;
else if (slot.anchoredPosition.y * -1f + slot.rect.height > parent.anchoredPosition.y + scrollRoot.rect.height)
movePos.y = (slot.anchoredPosition.y * -1f + slot.rect.height) - (parent.anchoredPosition.y + scrollRoot.rect.height);
}
if (movePos != Vector2.zero)
{
parent.DOAnchorPos(parent.anchoredPosition + movePos, moveTime).SetEase(Ease.InOutQuint).OnComplete(() => { if (act != null) act(); });
return false;
}
if (act != null) act();
return true;
}
사용 코드 예시
InputManager.GET.SetEventSystem(false); // 움직이는 동안 인풋 이벤트 막기 위해 넣은 코드로 InputManager는 제가 작성한 class고 SystemEvent.enabled를 세팅 해주는 기능을 호출 했습니다.
UITools.ScrollFocus(btn.transform.parent as RectTransform, 0.2f, () => { detailPanel.Selected(btn); InputManager.GET.SetEventSystem(true); });
상단에 코드를 이용해서 스크롤 된 아이템들의 위아래 짤린 Slot을 선택했을 때 자동으로 포커스 스크롤 되도록 한 것 시연 gif 입니다.
'Programming > Unity' 카테고리의 다른 글
UGUI Text에 배경 사이즈 자동 맞춤 (0) | 2021.03.24 |
---|---|
수식 문자를 계산 하기 (0) | 2021.02.16 |
댓글