Unity/기록

인벤토리 기능

우대비 2024. 6. 13. 01:58

 

 

 

인벤토리 간단한 기능을 구현했습니다.

아이템을 습득하면 아이템 ID를 입력받고 인벤토리 슬롯에 아이템의 ID가 저장됩니다.

 

 

JustKnight/Assets/Scripts/UI/InventoryManager.cs at main · znlsnel/JustKnight

2D Unity Project. Contribute to znlsnel/JustKnight development by creating an account on GitHub.

github.com

private void Awake() 
{
    _tempSlots.GetComponent<GraphicRaycaster>().enabled = false;	 
    _tempSlotText = _tempSlots.transform.Find("text").GetComponent<Text>();
    _tempSlotRectTransform = _tempSlots.GetComponent<RectTransform>();	
    foreach (Transform child in _inventorySlots.transform)
    { 
        if (child.name.Contains("ivnSlot")) 
        {
            int curIdx = _slots.Count;
            Text t = child.transform.Find("text")?.GetComponent<Text>();
            child.AddComponent<ButtonClickHandler>().InitButtonUpDown(
                () => { OnButtonUp(curIdx);}, 
                () => { OnButtonDown(curIdx); },
                () => { OnButtonEnter(curIdx);  },
                () => { OnButtonExit(curIdx);  }
            );  

            if (t != null) 
            {
                t.text= " - "; 
                _slots.Add(new Item(0, t)); 
            }
        }
    }
    gameObject.SetActive(false);
}

인벤토리를 처음 생성할 때 하위 슬롯들을 전부 불러오는 작업을 해주었습니다.

이후 버튼을 클릭했을 때, 클릭을 땠을 때, 마우스가 버튼 위에 있을때, 버튼 위에서 나왔을 때 실행되는 함수를 지정해 주었습니다.

 

 

JustKnight/Assets/Scripts/UI/ButtonClickHandler.cs at main · znlsnel/JustKnight

2D Unity Project. Contribute to znlsnel/JustKnight development by creating an account on GitHub.

github.com

public void InitButtonUpDown(Action up, Action down, Action enter = null, Action exit = null)
{
    _onButtonDown = down;
    _onButtonUp = up;
     _onButtonEnter = enter; 
     _onButtonExit = exit;
}

// Update is called once per frame

public void OnPointerDown(PointerEventData eventData)
{
    _onButtonDown?.Invoke();
}

public void OnPointerUp(PointerEventData eventData)
{
    _onButtonUp?.Invoke();
}

public void OnPointerEnter(PointerEventData eventData)
{
    _onButtonEnter?.Invoke();
}

public void OnPointerExit(PointerEventData eventData)
{ 
    _onButtonExit?.Invoke(); 
}

 

아이템 슬롯을 이동할 때는

임시 슬롯을 만들어서 슬롯을 들고 옮기는 것 처럼 만들었습니다. 

 

void OnButtonDown(int idx)
{
    _lastButtonDownTime = Time.time;
    startCoroutine = StartCoroutine(StartRelocateItem(idx)); 
}

void OnButtonUp(int idx) 
{ 
    float delay = Time.time - _lastButtonDownTime;
    if (delay < 0.2)
    {
        _equipSlots.transform.Find("index").GetComponent<Text>().text = _slots[idx]._name.text;  
    }

    if (startCoroutine != null) 
        StopCoroutine(startCoroutine);  

    if (isRelocateItem)
    {
        isRelocateItem = false;
        _tempSlots.SetActive(false);
        RelocateItemSlot(idx);
    }

} 

IEnumerator StartRelocateItem(int idx)
{
    yield return new WaitForSeconds(0.2f);
    
    InitTempSlot(idx);
    isRelocateItem = true;
    startCoroutine = null;
}

클릭 후 0.2초 안에 마우스에서 손을 때면 slot 선택으로 구분하고

0.2초가 넘어가면 slot을 이동하는 동작이 실행되게 하였습니다.

이때 코루틴을 이용하여 동작을 예약하였고 0.2초 안에 마우스에 손을 때면

코루틴이 취소되게 하였습니다.

 

void InitTempSlot(int idx)
{ 
    MoveTempSlot(); 
    _tempSlotText.text = _slots[idx]._name.text;
    _tempSlots.SetActive(true);
}

void RelocateItemSlot(int idx)
{
    if (_hoverSlotIdx < 0)
        return;

    string tmp = _slots[idx]._name.text;
    _slots[idx]._name.text = _slots[_hoverSlotIdx]._name.text;
    _slots[_hoverSlotIdx]._name.text = tmp; 
}

void MoveTempSlot() 
{
    Vector2 mousePos;
    RectTransformUtility.ScreenPointToLocalPointInRectangle(_tempSlotRectTransform.parent as RectTransform, Input.mousePosition, null, out mousePos);

    _tempSlotRectTransform.anchoredPosition = mousePos; 

}

 

 

LIST

'Unity > 기록' 카테고리의 다른 글

NPC 대화창 구현  (0) 2024.06.22
상호작용 기능 구현  (0) 2024.06.22
Item System 구현  (0) 2024.06.08
Unity Shader Hp Bar  (0) 2024.05.14
유니티 프로젝트 기록 - Monster  (0) 2024.05.13