본문 바로가기
Unity/소스코드

인벤토리 소스

by 세에레_freewing 2023. 3. 6.
반응형

item.cs

using UnityEngine;

[CreateAssetMenu]
public class Item : ScriptableObject
{
    public string itemName;
    public Sprite itemImage;
}

 

Slot.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    [SerializeField] Image image;  // Image Componet 담는곳

    private Item _item;
    public Item item {
        get { return _item; }  //슬롯의 item 정보를 넘겨줄때 사용
        set {
            _item = value;     //item에 들어오는 정보의 값은 _item에 저장됨
            if (_item != null) { 			//이 부분은 바로 밑 코드의 AddItem()과 FreshSlot() 함수에서 사용됨
                image.sprite = item.itemImage;
                image.color = new Color(1, 1, 1, 1);
            } else {
                image.color = new Color(1, 1, 1, 0);     
            }
        }
    } 
    
    //Inventory.cs 의 List<Item> items에 등록된 아이템이 있다면
    //itemImage를 image에 저장 그리고 Image의 알파 값을 1로 하여 이미지를 표시합니다.
    //만약 item이 null 이면 (빈슬롯 이면) Image의 알파 값 0을 주어 화면에 표시하지 않습니다.
}

 

Inventory.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    public List<Item> items;	//아이템을 담을 리스트

    [SerializeField]
    private Transform slotParent;	//Slot의 부모가 되는 Bag을 담을 곳
    [SerializeField]
    private Slot[] slots;	//Bag의 하위에 등록된 Slot을 담을 곳

    private void OnValidate() {									//OnValidate()의 기능은 유니티 에디터에서 바로 작동을 하는 역할을 합니다.
        slots = slotParent.GetComponentsInChildren<Slot>();		//처음 인벤토리에 소스를 등록하시면 Console창에 에러가 뜨지만 Bag을 넣어 주시면 
    }															//slots에 Slot들이 자동 등록됩니다.

    void Awake() {	//게임이 시작되면 items에 들어 있는 아이템을 인벤토리에 넣어 줍니다.
        FreshSlot();
    }

    public void FreshSlot() {									//FreshSlot의 역할은 아이템이 들어오거나 나가면 Slot의 내용을 다시 정리하여 화면에 보여 주는 기능을 합니다.
        int i = 0;												//int i = 0을 외부에 선언한 건 두 개의 For 문에 같은 i의 값을 사용하기 위해서입니다.		
        for (; i < items.Count && i < slots.Length; i++) {		//첫 for문은 items에 들어 있는 수만큼 slots에 차례대로 item을 넣어 줍니다.
            slots[i].item = items[i];							//slot에 item이 들어가면 Slot.cs에 선언된 item의 set 안의 내용이 실행되어 해당 슬롯에 이미지를 표시하게 됩니다.
        }														//"i < items.Count && i < slots.Length" i의 값이 items와 slots 두 개의 값 보다 작아야만 돌아가는 구조입니다.
        for (; i < slots.Length; i++) {							//slot에 아이템을 다 저장하고 난 후에도 slot이 남아 있다면 다음 for문이 실행되어 빈 슬롯들은 모두 null 처리하게 
																//됩니다.		
            slots[i].item = null;
        }
    }
																//Item이 Null 일경우 Image 알파 값 0을 주어 Image를 숨겨 버립니다
    public void AddItem(Item _item) {
        if (items.Count < slots.Length) {
            items.Add(_item);
            FreshSlot();
        } else {
            print("슬롯이 가득 차 있습니다.");
        }
    }
}

 

 

자료 출처 : https://geojun.tistory.com/62

반응형