게임개발/스터디

[스터디] 재사용 스크롤뷰 구현 방법

감물 2024. 3. 15. 15:50

● 사용 목적 :

재사용 스크롤뷰를 사용하여, 컨텐츠가 늘어나도 인게임 내 퍼포먼스가 저하되지 않도록 관리하기 위함

 

 

사용 방법 : 

    private void CreateContent() // 컨텐츠 생성
    {
        SlotList = new List<Slot>();
        for (int i = 0; i < _slotCount; i++)
        {
            Slot slot = Instantiate(SlotPrefab, ContentRectTr);
            slot.SetInfo(i);

            SlotList.Add(slot);
        }
    }

    private void RecycleContent(Slot slot) // 리사이클 수행
    {
        float contentPosX = ContentRectTr.anchoredPosition.x;

        // 왼쪽으로 땡겼을 때 위치 조정
        if (slot.transform.localPosition.x + contentPosX < -_slotWidth - _slotOffset)
        {
            if (slot.GetCount() + _slotCount > Grid.constraintCount - 1) return;

           // 왼쪽 스크롤 끝 한계 지정


            slot.transform.localPosition += new Vector3(_slotCount * _slotWidth, 0);
            slot.SetInfo( slot.GetCount() + _slotCount );
        }


        // 오른쪽으로 땡겼을 때 위치 조정
        else if (slot.transform.localPosition.x + contentPosX 

        > ScrollRectTr.rect.width + _slotOffset)
        {
            if (slot.GetCount() - _slotCount < 0) return; // 오른쪽 스크롤 끝 한계 지정


            slot.transform.localPosition -= new Vector3(_slotCount * _slotWidth, 0);
            slot.SetInfo( slot.GetCount() - _slotCount );
        }
    }

    public void ResetContent() // On&Off 시 위치 및 정보 초기화
    {
        ContentRectTr.anchoredPosition = Vector3.zero;
        for (int i = 0; i < _slotCount; i++) // 슬롯 정보 초기화
            SlotList[i].SetInfo(i);
    }

 

 

 

유의 사항 :

1. slotOffset 값을 적절히 조절해 주어야 함(Content width 및 Slot width는 구현마다 다를 수있음으로)

2. Content에 GridLayoutGroup 컴포넌트를 붙이고 Constraint Count를 entireCount 수만큼 조정해 주어야 함

   (재사용될 슬롯 개수는 작아도 Content Size는 슬롯이 전체 개수만큼 들어갈 크기를 가지고 있어야 하기 때문)

3. On/Off 시 Content들의 위치를 초기화 해주어야 함(Content RectTransform 값 초기화 필요)