728x90

오늘은 인벤토리 구현 마지막 단계이다 

 

일단은 아이템 리스트는 액셀로 관리하는게 좋다고해서 

이런식으로 대충 만들어놓고

 

이것을 텍스트로 저장해서 유니티에 넣어준다음 

 

이것을 스크립트에서 아이템 리스트에 넣어줘야하기때문에 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Newtonsoft.Json;
using UnityEngine.UI;
[System.Serializable]
public class Item
{
    public Item(string _ItemType, string _Type, string _Name, string _Explain, string _Number, bool _isUsing) // 생성자 생성 
    {
        ItemType = _ItemType; // 밑에 값에다가 대입 해준다 
        Type = _Type; //이하동문 
        Name = _Name;
        Explain = _Explain;
        Number = _Number;
        isUsing = _isUsing;
    }
    public string ItemType, Type, Name, Explain, Number;
    public bool isUsing;
}

이런식으로 작성해서 받을수있게 해준다음

 

public List<Item> Alltem;

void Start()
    {
        string[] line = ItemDatabase.text.Substring(0, ItemDatabase.text.Length - 1).Split('\n'); // 아이템 데이터 베이스가 저장되면 마지막줄은 엔터라서 엔터빼고 받기위해서  
        for (int i = 0; i < line.Length; i++)
        {
            string[] row = line[i].Split('\t');// 라인 0 번을 탭으로 나누고 넣어준다 row 에 
            Alltem.Add(new Item(row[0], row[1], row[2], row[3], row[4], row[5] == "TRUE"));// 아이템타입,타입,이름,설명,갯수,장착여부 를 넘겨준다 . 
        }

        Load();
    }

이런식으로 작성하게되면 Allitem에 아이템텍스트에 있는것들이 할당되어 들어가게된다 

 

 void Save()
    {
        string jdata = JsonConvert.SerializeObject(MyItemList); //처음할대는 MyItemList를 AllItem으로 변경 모든 Item 저장을위해  string에 내 아이템리스트를 json으로 바꿔줘서 넣어주고 
        File.WriteAllText(Application.dataPath + "/Resources/MyItemText.txt", jdata); // 이파일을 Resources 폴더에 MyItemText jdata로 저장해준다 
        TabClick(curTab); // 탭클릭호출 
    }

    void Load()
    {
        string jdata = File.ReadAllText(Application.dataPath + "/Resources/MyItemText.txt"); // 내아이템 리스트 를 읽어오고 
        MyItemList = JsonConvert.DeserializeObject<List<Item>>(jdata); // Convert하여 Myitemlist에 넣어준다 
        TabClick(curTab); // 처음 탭클릭 호출
    }

 

실행하고 끄면 저장과 로드를 이런식으로 하게되고

 

 public void TabClick(string tabname)// 탭클릭시 온클릭이벤트 
    {
        curTab = tabname; // 현재탭은 탭네임 받기 
        if(tabname != "All") // 만약 탭타입이 all 이 아니면 
        {
            CurItemList = MyItemList.FindAll(x => x.ItemType == tabname); // 내 아이템 리스트에서 아이템 타입과 탭네임이 같은 것을 찾아라 
            for (int i = 0; i < Slot.Length; i++)// 슬롯갯수만큼 돌려주고 
            {
                bool isExistSlot = i < CurItemList.Count;
                
                Slot[i].SetActive(isExistSlot); // 아이템 카테고리에 맞는 아이템 만큼 슬롯 생성 
                
                    Slot[i].GetComponentInChildren<Text>().text = isExistSlot ? CurItemList[i].Number : ""; // 텍스트 에 갯수 표현 
                if(isExistSlot) // 아이템이 존재한다면 
                {
                    ItemImage[i].sprite = ItemSprite[Alltem.FindIndex(x=> x.Name == CurItemList[i].Name)]; // 아이템 이미지 스프라이트 에다가 아이템 스프라이트를 넣는데 AllItem 에서 CurItem과 이름이 같은것을 찾고 인덱스에 해당되는 이미지 할당 
                }
             
                if (i < CurItemList.Count && CurItemList[i].isUsing == true) // 만약 현재 아이템이 사용중이라면 
                {
                    Slot[i].transform.Find("Eqip").gameObject.SetActive(true); // 장착중 표시 

                }
                else if(i < CurItemList.Count && CurItemList[i].isUsing ==false) // 아니라면 
                {
                    Slot[i].transform.Find("Eqip").gameObject.SetActive(false); // 장착중 꺼주기 이하동문 
                }

                

            }
        }
        else
        {

            CurItemList = MyItemList; // all 이면 모두 넣어라 
            for (int i = 0; i < Slot.Length; i++)
            {
                bool isExistSlot = i < CurItemList.Count;

                Slot[i].SetActive(true);// 모든 아이템 카테고리기때문에 슬롯을 다그려준다 
                Slot[i].GetComponentInChildren<Text>().text = isExistSlot ? CurItemList[i].Number : "";
                if(isExistSlot) // 아이템이 존재한다면 
                {
                    ItemImage[i].sprite = ItemSprite[Alltem.FindIndex(x => x.Name == CurItemList[i].Name)]; // 아이템 이미지 스프라이트는 
                }
                
                if (i < CurItemList.Count && CurItemList[i].isUsing == true)
                {
                    Slot[i].transform.Find("Eqip").gameObject.SetActive(true);

                }
                else if (i < CurItemList.Count && CurItemList[i].isUsing == false)
                {
                    Slot[i].transform.Find("Eqip").gameObject.SetActive(false);
                }
            }
        }

       
        switch(tabname) // 셀렉트 이미지 활성화 위해 
        {
            case "All":
                SelectImg[0].enabled = true;
                SelectImg[1].enabled = false;
                SelectImg[2].enabled = false; 
                SelectImg[3].enabled = false; 
                break;
            case "Eqipment":
                SelectImg[0].enabled = false;
                SelectImg[1].enabled = true;
                SelectImg[2].enabled = false;
                SelectImg[3].enabled = false;
                break;
            case "Accessory":
                SelectImg[0].enabled = false;
                SelectImg[1].enabled = false;
                SelectImg[2].enabled = true;
                SelectImg[3].enabled = false;
                break;
            case "Potion":
                SelectImg[0].enabled = false;
                SelectImg[1].enabled = false;
                SelectImg[2].enabled = false;
                SelectImg[3].enabled = true;

                break;

        }
    }

 

아이템을 카테고리별로 보이게 하기위해 이런식으로 탭클릭 함수를 만들어주고 

 public void SlotClick(int slotNum)//슬롯클릭때
    {
        Item CurItem = CurItemList[slotNum]; // 현재 아이템은 슬롯넘버 
        Item UsingItem;




            switch (CurItem.Type) // 클릭한 아이템 타입구별을위해선언 
            {
                case "Armor": // 타입이 Armor 라면 
                     UsingItem = MyItemList.Find(x => x.Type == "Armor" && x.isUsing == true); // 내아이템중 타입이 아머이면서 사용중인것을 찾는다.
                    if(UsingItem != null && CurItem != UsingItem) // 만약 사용중인Armor 가 없고 클릭한 아이템 사용중인것과 같지않다면 
                    {
                        UsingItem.isUsing = false; // 사용중인 Armor false 
                        CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                    }
                    else
                    {
                        CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                    }
                    break;
                case "Helmet":
                UsingItem = MyItemList.Find(x => x.Type == "Helmet" && x.isUsing == true); // 내아이템중 타입이 아머인것을 찾는다.
                if (UsingItem != null && CurItem != UsingItem)
                {
                    UsingItem.isUsing = false;
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                else
                {
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                break;
                case "Glove":
                UsingItem = MyItemList.Find(x => x.Type == "Glove" && x.isUsing == true);
                if (UsingItem != null && CurItem != UsingItem)
                {
                    UsingItem.isUsing = false;
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                else
                {
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                break;
                case "Wepon":
                UsingItem = MyItemList.Find(x => x.Type == "Wepon" && x.isUsing == true);
                if (UsingItem != null && CurItem != UsingItem)
                {
                    UsingItem.isUsing = false;
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                else
                {
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                break;
                case "Shose":
                UsingItem = MyItemList.Find(x => x.Type == "Shose" && x.isUsing == true);
                if (UsingItem != null && CurItem != UsingItem)
                {
                    UsingItem.isUsing = false;
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                else
                {
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                break;
                case "Ring":
                UsingItem = MyItemList.Find(x => x.Type == "Ring" && x.isUsing == true);
                if (UsingItem != null && CurItem != UsingItem)
                {
                    UsingItem.isUsing = false;
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                else
                {
                    CurItem.isUsing = !CurItem.isUsing; // 현재 클릭한 슬롯 false 면 true 로 true 면 false 로 변경. 이하동문 
                }
                break;
            }
        
       
        Save();// json 데이터로 저장 사용중인것들 
    }

 

슬롯 클릭 함수도 만들어준다 

 

코드 첫부분에는

  public TextAsset ItemDatabase;// 아이템 데이터베이스를 연결해주기위해 선언 
    public List<Item> Alltem, MyItemList, CurItemList; //아이템을 리스트 해주기위해
    public string curTab = "All";//처음 탭 타입 
    public Image[] SelectImg; // 아이템 셀렉 이미지 켜주기위해 배열로받고
    public GameObject[] Slot;//슬롯을 넣기위해 
    public Image[] ItemImage; // 슬롯 아이템 이미지 연결 
    public Sprite[] ItemSprite; // 아이템 데이터 베이스순서에 맞게 스프라이트 연결

 

이런식으로 선언해준다 

slot에 슬롯을 끌어다 넣어줬는데 이경우는 content의 자식오브젝트를 다넣어주는거로도 가능하다.

아이템 이미지에도 슬롯이 가지고있는 아이템 아이콘 이미지를 연결시켜 주었는데 이경우에도 

 

슬롯 자식에 ItemIcon 이미지를 할당해줘도 된다. (스크립트 안에서)

 

아이템 스프라이트에는 

 

Eqipment	Weapon	초보자용 활	초보자용 활이다	1	FALSE
Eqipment	Helmet	초보자용 헬멧	초보자용 헬멧이다	1	FALSE
Eqipment	Armor	초보자용 자켓	초보자용 자켓이다	1	FALSE
Eqipment	Glove	초보자용 장갑	초보자용 장갑이다	1	FALSE
Eqipment	Shose	초보자용 신발	초보자용 신발이다	1	FALSE
Accessory	Ring	허름한 반지	허름한 반지다	1	FALSE
Potion	HP	초보자용 HP회복 포션	HP 50 회복 포션	1	
Potion	MP	초보자용 MP회복 포션	MP 20 회복 포션	1

아까 내가 저장했던 AllItem 에 순서에맞게 스프라이트를 할당해준다.

 

 

 

실행영상

 

 

 

 

내일은 캐릭터 장비창을 옆에 구현하고 랜더 텍스쳐로 캐릭터 그려주면서 아이템에 마우스를 가져다 올리면 팝업창이 나타나서 아이템 정보가 뜨게끔 할 예정이다. 

 

인벤토리를 접근할수있게 아이콘을 만들어줄 예정이다. 

 

역시 인벤토리가 제일 어려운거같다 근데 json으로 데이터를 저장하기때문에 서버에 남기기 쉬울거같다. 

반응형