Unity/유니티 기본
[4.20] 아이템 습득 후 인벤토리에 표시
ljw4104
2021. 4. 20. 18:11
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);
}
}