본문 바로가기
게임개발/게임 UI.UX 프로그래밍

인벤토리 그리드 만들기2 : 아이템 추가하기

by pudding81 2024. 2. 24.

 

아이템 추가에 오류 발생

 

 

아이템을 추가할 때 바로 화면에 반영되지 않고 나갔다가 다시 들어오면 보임

오잉???

 

가지고 있던 아이템은 버튼 누르면 수량증가가 바로 보여짐.

 

뭐가 문제냐~~~~~~~????

 

 

 

using System;


public class ItemData //제이슨 파일에 맞추기
{
      public int id;
      public string name;
      public int type;
      public string sprite_name;
      public int sell_price;
}

 

 

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

public class ItemInfo //변하는 데이터
{

    public int id;
    public int amount; // 아이템 수량
    


    //생성자 필요함
    public ItemInfo(int id, int amount=1)
    {
        this.id = id;
        this.amount = amount;
       
    }
}

 

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

public class InventoryInfo //변하는 데이터
{
    public List<ItemInfo> itemInfos;



    //생성자 필요함

    public void Init()
    {
        this.itemInfos = new List<ItemInfo>(); //신규유저일때만 호출


    }

  

}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.Experimental;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;
using static UnityEditor.Progress;

public class ItemView : MonoBehaviour
{
    public Image icon;
    public GameObject focusGo;
    public TMP_Text amount;

    private int id;

    // 버튼 클릭 아이템 판매
    public Button btn;
    public Button Btn => this.btn;
    



    public void Init(int id, Sprite sprite, int amount) 
    {
        this.id = id;
        this.icon.sprite = sprite;
        this.icon.SetNativeSize();
        this.amount.text = amount.ToString();
        this.amount.gameObject.SetActive(amount > 1);


    }


}

 

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class DataManager
{
    //싱글톤 패턴 
    //클래스에 인스턴스가 한개
    //전역적으로 접근 가능하다


    //public static readonly 변수를 정의하고 인스턴스를 생성해라 
    public static readonly DataManager Instance = new DataManager();


    private Dictionary<int, ItemData> dicItemDatas;
    

    //생성자 필요없음 딕셔너리에서 생성됨.
    private DataManager()
    {

    }



    public void LoadItemData()
    {
        TextAsset asset = Resources.Load<TextAsset>("item_data");
        string json = asset.text;
        //역직렬화 
        ItemData[] datas = JsonConvert.DeserializeObject<ItemData[]>(json);
        //Linq 사용 
        this.dicItemDatas = datas.ToDictionary(x => x.id);
        Debug.LogFormat("dicItemDatas.Count: {0}", dicItemDatas.Count);
    }

 

    public ItemData GetItemData(int id)
    {
       if(this.dicItemDatas.ContainsKey(id))
        {
            return this.dicItemDatas[id];
        }

        Debug.LogFormat("key:{0}not found",id);
        return null;

    }

    public ItemData GetRandomItemData()
    {
        var randId = Random.Range(0,this.dicItemDatas.Count)+100;
        return this.GetItemData(randId);
    }

}
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class InfoManager
{
    public static readonly InfoManager Instance = new InfoManager();

    public InventoryInfo InventoryInfo
    {
        get; set;
    }
    private InfoManager() { }

    public void SaveLocal()  // 인포에 데이터 저장하기 
    {
        Debug.Log("<color=yellow>SaveLocal</color>");
        var json = JsonConvert.SerializeObject(this.InventoryInfo);
        string path = Path.Combine(Application.persistentDataPath, "inventory_info.json");
        Debug.Log(path);
        File.WriteAllText(path, json);
        Debug.Log("save complete!");
    }


}
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.U2D;

public class AtlasManager : MonoBehaviour
{
    public static AtlasManager Instance
    {
        get;
        private set;
    }

    [SerializeField] private List<SpriteAtlas> atlases;

    private Dictionary<string, SpriteAtlas> dicAtlases;
    //싱글톤 
    private void Awake()
    {
        Instance = this;
    }

    public void Init()
    {

        this.dicAtlases = this.atlases.ToDictionary(x => x.name);
        Debug.LogFormat("this.dicAtlases.Count: {0}", this.dicAtlases.Count);
    }

    public SpriteAtlas GetAtlas(string name)    //UIShop
    {

        return this.atlases.Find(x => x.name == name);
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class Scrollview : MonoBehaviour
{
    public Transform content;
    public GameObject cellviewPrefab;
    public GameObject NoitemGo;
    private const int overcount = 24; //스크롤 작동 정지 갯수 
    private int index;


    public void Init()
    {
        this.index= InfoManager.Instance.InventoryInfo.itemInfos.Count;

        Debug.LogFormat("아이템수 {0}",index);

        this.NoitemGo.SetActive( index== 0);

        this.CreateCellView();
  

        // 아이템이 24개가 넘으면 스크롤이 작동함
        this.GetComponent<ScrollRect>().vertical = index > overcount;

    }

   

   
    public void Refresh()
    {
        //아이템을 모두 제거하고
        foreach (Transform child in this.content)
        {
            Destroy(child.gameObject);
        }

        this.CreateCellView(); //아이템프리팹 생성하기


        this.NoitemGo.SetActive(index == 0);


    }

  
    private void CreateCellView()
    {
        for (int i = 0; i < index; i++)
        {
            GameObject go = Instantiate(cellviewPrefab, content);
            var cellview = go.GetComponent<ItemView>();

            var info = InfoManager.Instance.InventoryInfo.itemInfos[i];
            var data = DataManager.Instance.GetItemData(info.id);
            var atlas = AtlasManager.Instance.GetAtlas("UIInventoryAtlas");
            var sprite = atlas.GetSprite(data.sprite_name);
            var amount = info.amount;
            var id = info.id;

            cellview.Init(id, sprite, amount);

        }
    }
}

 

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


public class UIInventory : MonoBehaviour
{
    public Scrollview scrollVeiw;
    public Button btnGetitem;


    public void Init()
    {
        //Getitem btn을 클릭하면
        this.btnGetitem.onClick.AddListener(() =>
        {

           var data = DataManager.Instance.GetRandomItemData();
           var id = data.id;   
           var foundInfo= InfoManager.Instance.InventoryInfo.itemInfos.Find(x=>x.id==id);

            if (foundInfo == null)
            {
                ItemInfo info =new ItemInfo(id);
               InfoManager.Instance.InventoryInfo.itemInfos.Add(info); //최초아이템 획득

            }
            else
            {
                foundInfo.amount++;
            }

            //save
            InfoManager.Instance.SaveLocal();
            
            this.scrollVeiw.Refresh();



        });


        this.scrollVeiw.Init();


        



    }
}
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class Main : MonoBehaviour
{
   public UIInventory uiinventory;
   public InventoryInfo inventoryInfo;

    void Start()
    {
        DataManager.Instance.LoadItemData();
        AtlasManager.Instance.Init();


        Init(); //신규유저 기존유저 판단해서 인포저장 
        this.uiinventory.Init();

    }

    private void Init() 
    {

        string path = Path.Combine(Application.persistentDataPath, "inventory_info.json");

        //기존 유저 
        if (File.Exists(path))
        {
            Debug.Log("<color=yellow>기존유저</color>");
            string json = File.ReadAllText(path);
            inventoryInfo = JsonConvert.DeserializeObject<InventoryInfo>(json);
            InfoManager.Instance.InventoryInfo = inventoryInfo;
        }
        //신규 유저
        else
        {
            Debug.Log("<color=yellow>신규유저</color>");
            inventoryInfo = new InventoryInfo();
            inventoryInfo.Init();
            InfoManager.Instance.InventoryInfo = inventoryInfo;
            InfoManager.Instance.SaveLocal();
        }

       
    }


}