Use Json to realize the data storage of the backpack system (two)

1. Art preparation (be an axe)

Make an axe in blender as an object to be picked up.
Insert picture description here
Insert picture description here
Insert picture description here
Put it here and find that the color of the texture has changed slightly. I am using URP here. I don't know the reason. I would like to ask everyone for advice. Thank you for the solution.

Two, Json data is connected with the GUI interface

Every time we eat the axe, we need to put the axe data into the backpack (list of the backpack class),
so we need an ItemOnWorld, which is the interaction between world objects and backpack data

public class ItemOnWorld : MonoBehaviour
{
    
    
    [Header("物体所属的背包")]
    public BagManager Bag;

    private Item item=new Item();
    [Header("物体属性")]
    public string name;
    public int number;
    public string des;
    public string type;
    public string spritePath;


    private void Awake()//将属性赋予物体
    {
    
    
        item.name = name;
        item.number = number;
        item.des = des;
        item.type = type;
        item.spritePath = spritePath;
    }

    private void OnCollisionEnter(Collision collision)
    {
    
    
        if (collision.gameObject.CompareTag("Player"))
        {
    
    
            AddNewItem();
            Destroy(this.gameObject);
        }
    }

    private void AddNewItem()
    {
    
    

        foreach (var m_item in Bag.Mydata.bagData)//检测有没有同名物体,没有就添加
        {
    
    
            if (m_item.name==item.name)
            {
    
    
                m_item.number += 1;
                Debug.Log("物体:" + item.name + ",的数量:" + m_item.number);
                return;
            }

        }
        Bag.Mydata.bagData.Add(item);
        Debug.Log("加入物体");
    }
}

Hang this on the object, fill in the parameters, and then test, copy 5 axes, and then check whether the data is correctly added to the backpack data The
Insert picture description here
test is successful
Insert picture description here

Third, link the data with the interface of the backpack

, We create a BagGuiManager script to manage the GUI interface, all we have to do is to use this script to create corresponding pictures based on the backpack data.
Write a RefreshItem method to refresh the backpack (regenerate objects based on the backpack data)
CreatGUIItem assigns the slot according to the incoming item, (the specific implementation of generating GUI based on the item data in the backpack)

using UnityEngine;
using UnityEngine.UI;

public class BagGuiManager : MonoBehaviour
{
    
    
    public static BagGuiManager instacne;

    private void Awake()
    {
    
    
        if (instacne != null)
        {
    
    
            Destroy(this);
        }
        instacne = this;
    }

    [Header("背包")]
    public BagManager bag;

    public Slot slot;//对应的格子
    public GameObject slotGrid;
    public Text itemDes;//物品描述

    private void OnEnable()
    {
    
    
        RefreshItem();
        itemDes.text = "";
    }

    public void CreatGUIItem(Item item)
    {
    
    
        Slot newItem = Instantiate(slot, slotGrid.transform, false);//为item,实例化一个slot并赋值
      
        newItem.soltItem = item;
        newItem.name = item.name;
        newItem.number.text = item.number.ToString();
        Debug.Log("显示的数量:" + item.number);

        //显示图片
        GameObject m_Image = Resources.Load(item.spritePath) as GameObject;
        newItem.soltImage = m_Image.GetComponent<Image>();
    }

    public void RefreshItem()//刷新数量,重新生成
    {
    
    
        for (int i = 0; i < instacne.slotGrid.transform.childCount; i++)
        {
    
    
            if (instacne.slotGrid.transform.childCount == 0)
            {
    
    
                Debug.Log("没有物体可销毁");
                break;
            }
            Destroy(instacne.slotGrid.transform.GetChild(i).gameObject);
            Debug.LogError("Destory");
        }

        //foreach (var item in bag.Mydata.bagData)
        //{
    
    
        //
        //    CreatGUIItem(item);
        //}
        for (int i = 0; i < bag.Mydata.bagData.Count; i++)
        {
    
    
            Debug.Log("重新生成");
            CreatGUIItem(bag.Mydata.bagData[i]);
        }
    }
}

We use for or foreach to traverse the backpack data, create a slot for each item, and assign the item data to the slot. We add a button to the solt, and when clicked, the description of the item is assigned to the position of the backpack GUI description (below the backpack)

using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    
    
    public Item soltItem;
    public string name;
    public Image soltImage;
    public Text number;

    public void ItemOnClick()
    {
    
    
        Debug.Log("点击solt");
        BagGuiManager.instacne.itemDes.text = soltItem.des;
    }
}

Slot is a prefab. It is the picture displayed in the backpack. It has the number and attributes of the picture. Creating a slot is to create the ui in the backpack.
The picture assignment here uses the resource loading method.
First, the picture will be done. The prefab is placed in the Resources directory, and the prefab is loaded according to the path to obtain its picture and assign values. (As loading method)

GameObject m_Image = Resources.Load(item.spritePath) as GameObject;
newItem.soltImage.sprite = m_Image.GetComponent<Image>().sprite;

Second, through Resouces.Load generic loading
(generic loading method)

newItem.soltImage.sprite = Resources.Load<Sprite>(item.spritePath);//不能使用as Sprite,
//会失败,要使用泛型的加载

Insert picture description here
Finally, we need to refresh the GUI backpack every time we add a new object, that is, when we encounter an object in ItemOnWorld and add it to the data backpack, add a step to refresh the GUI interface and call the SaveGame method in BagManager
Insert picture description here
Insert picture description here

Successfully link the backpack data with the backpack GUI.
Insert picture description here
Finally, we call the reading method in the backpack script. At the beginning of each game, we read the Json data and refresh the backpack GUI.
Insert picture description here
Insert picture description here
Insert picture description here

Four, complete code reference

using UnityEngine;
using UnityEngine.UI;

public class BagGuiManager : MonoBehaviour
{
    
    
    public static BagGuiManager instacne;

    private void Awake()
    {
    
    
        if (instacne != null)
        {
    
    
            Destroy(this);
        }
        instacne = this;
    }

    [Header("背包")]
    public BagManager bag;

    public Slot slot;
    public GameObject slotGrid;
    public Text itemDes;

    private void OnEnable()
    {
    
    
        RefreshItem();
        itemDes.text = "";
    }

    public void CreatGUIItem(Item item)
    {
    
    
        Slot newItem = Instantiate(slot, slotGrid.transform, false);
        //newItem.gameObject.transform.SetParent(slotGrid.transform,false);//设置父物体
        newItem.soltItem = item;
        newItem.name = item.name;
        newItem.number.text = item.number.ToString();
        Debug.Log("显示的数量:" + item.number);

        //显示图片
        
        //GameObject m_Image = Resources.Load(item.spritePath) as GameObject;
        //newItem.soltImage.sprite = m_Image.GetComponent<Image>().sprite;//做成预制体,然后通过加载预制体赋予图片,as 加载方式

        newItem.soltImage.sprite = Resources.Load<Sprite>(item.spritePath);//不能使用as Sprite,会失败,要使用泛型的加载
    }

    public void RefreshItem()//刷新数量,重新生成
    {
    
    
        for (int i = 0; i < instacne.slotGrid.transform.childCount; i++)
        {
    
    
            if (instacne.slotGrid.transform.childCount == 0)
            {
    
    
                Debug.Log("没有物体可销毁");
                break;
            }
            Destroy(instacne.slotGrid.transform.GetChild(i).gameObject);
            Debug.LogError("Destory");
        }

        //foreach (var item in bag.Mydata.bagData)
        //{
    
    
        //
        //    CreatGUIItem(item);
        //}
        for (int i = 0; i < bag.Mydata.bagData.Count; i++)
        {
    
    
            Debug.Log("重新生成");
            CreatGUIItem(bag.Mydata.bagData[i]);
        }
    }
}
using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    
    
    public Item soltItem;
    public string name;
    public Image soltImage;
    public Text number;

    public void ItemOnClick()
    {
    
    
        Debug.Log("点击solt");
        BagGuiManager.instacne.itemDes.text = soltItem.des;
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemOnWorld : MonoBehaviour
{
    
    
    //[Header("物体所属的背包")]
    //public BagManager Bag;

    private Item item=new Item();
    [Header("物体属性")]
    public string name;
    public int number;
    public string des;
    public string type;
    public string spritePath;


    private void Awake()//将属性赋予物体
    {
    
    
        item.name = name;
        item.number = number;
        item.des = des;
        item.type = type;
        item.spritePath = spritePath;
    }

    private void OnCollisionEnter(Collision collision)
    {
    
    
        if (collision.gameObject.CompareTag("Player"))
        {
    
    
            AddNewItem();
            Destroy(this.gameObject);
        }
    }

    private void AddNewItem()
    {
    
    

        foreach (var m_item in BagManager.instacne.Mydata.bagData)//检测有没有同名物体,没有就添加
        {
    
    
            if (m_item.name==item.name)
            {
    
    
                m_item.number += number;
                Debug.Log("物体:" + item.name + ",的数量:" + m_item.number);
                BagGuiManager.instacne.RefreshItem();
                return;
            }

        }
        BagManager.instacne.Mydata.bagData.Add(item);
        Debug.Log("加入物体");
        BagGuiManager.instacne.RefreshItem();
        // BagGuiManager.instacne.CreatGUIItem(item);

    }
}

5. Warehouse address

https://github.com/euphoriaer/Mybag.git

Guess you like

Origin blog.csdn.net/euphorias/article/details/108901074