Notice
Recent Posts
Recent Comments
Link
스토리지
[4.20] 아이템 습득 후 인벤토리에 표시 본문
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);
}
}
'Unity > 유니티 기본' 카테고리의 다른 글
[4.21] 게임데이터를 바탕으로 스테이지 씬 만들기 (0) | 2021.04.21 |
---|---|
[4.20] Atlas (0) | 2021.04.20 |
[4.16] 유니티에서 Json파일 읽어오기 (0) | 2021.04.16 |
[4.16] json에서 데이터를 불러오고 게임오브젝트 만들기 (0) | 2021.04.16 |
[4.16] 씬 전환 (0) | 2021.04.16 |
Comments