Unity/유니티 기본

[4.20] 아이템 습득 후 인벤토리에 표시

ljw4104 2021. 4. 20. 18:11

달려가서 아이템과 닿으면 아이템이 사라지고 인벤토리에 뜬다.

 

InGame은 맨위에서 전달역할만 수행함.
Grid Layout Group이 적용되어 가로 세로 모두 일정한 간격으로 프리팹을 생성할 수 있다.
인벤토리 팝업의 구성과 Item List 오브젝트에 Grid Layout Group이 들어갔다.

 

Grid Layout Group에 아이템 프리팹을 붙이는 코드.

 

Inventory.cs

public void AddItem(int id)
{
    var go = Instantiate(this.prefab, this.gridLayout);
    var uiItem = go.GetComponent<UIItem>();
    var icon = this.atlas.GetSprite("inventory_item_sword_A");
    //임시로 문자열을 삽입했지만 Json을 읽어 인자 id에 해당하는 sprite_name을 가져와서 붙인다.
    uiItem.Init(id, icon);
}

InGame.cs // 게임의 모든것을 관리한다.

using UnityEngine;

public class InGame : MonoBehaviour
{
    public Inventory uiInventory;
    private Hero hero;
    // Start is called before the first frame update
    void Start()
    {
        this.hero = FindObjectOfType<Hero>();
        this.hero.OnGet = (id) =>
        {
            Debug.LogFormat("아이템({0})을 획득하였습니다.", id);
            this.hero.Stop();
            this.uiInventory.AddItem(id);
        };
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.I))
        {
            uiInventory.gameObject.SetActive(true);
        }
    }
}

Hero.cs  // InGame에게 아이템과 부딪혔다고 알린 후 아이템을 파괴한다.

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Item"))
    {
        this.OnGet(other.GetComponent<Item>().id);
        Destroy(other.gameObject);
    }
}