부트캠프/Unity [ 스파르타 ]
[Unity] 인벤토리 관하여
맏난거
2025. 1. 9. 18:18
Inventory // 게임 시스템적인 부분
public class Inventory : MonoBehaviour
{
#region Singleton // 싱글톤 부분
public static Inventory instance;
private void Awake()
{
if(instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
}
#endregion
public delegate void OnSlotCountChange(int val);
public OnSlotCountChange onSlotCountChange;
private int slotCnt;
public int SlotCnt
{
get => slotCnt;
set
{
slotCnt = value;
onSlotCountChange.Invoke(slotCnt); // Invoke() 델리게이트 호출 함수
}
}
public void InitInventory(int slotCount = 3)
{
SlotCnt = slotCount;
}
public void AddSlot ()
{
SlotCnt++;
}
}
InventoryUI // UI관련
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InventoryUI : MonoBehaviour
{
Inventory inven;
public GameObject inventoryPanel; // 인벤토리 게임오브젝트
bool activeInventory = false; // 활성화, 비활성화
[Tooltip ("Slot 프리펩을 추가")]
public Slot[] slots; // 슬롯 배열
[Tooltip ("InventoryUI오브젝트 자식에 Contents오브젝트 추가")]
public Transform slotHolder; // Contents 게임오브젝트
// Start is called before the first frame update
private void SetSlot(int val)
{
for (int i = 0; i < slots.Length; i++)
{
if (i < inven.SlotCnt) slots[i].GetComponent<Button>().interactable = true;
else slots[i].GetComponent<Button>().interactable = false;
}
}
void Start()
{
inven = Inventory.instance;
inventoryPanel.SetActive(activeInventory);
slots = inventoryPanel.GetComponentsInChildren<Slot>(); // 자식 오브젝트들의 Slot컴포넌트를 가져온다.
inven.onSlotCountChange += SetSlot; // += 이용해서 델리게이트 함수 콜백
inven.InitInventory();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.I))
{
activeInventory = !activeInventory;
inventoryPanel.SetActive(activeInventory);
}
}
}
인벤토리 일부분
참고영상:
https://youtu.be/iGyd54-mIiE?feature=shared
Inventory 스크립트 Start 이벤크콜 함수에 SlotCnt 호출하는 부분이 있어서
아직 델리게이트 함수를 못받은 상황이기때문에 NullReference에러 즉 널참조하고 있기때문에 위 영상에서는
스크립트 실행순서를 바꿔서 해결했지만, 저는 이게 불편해서 Start 이벤트콜을 지우고 AddSlot이라는 함수를 따로 만들어서 사용했습니다.