Не получается сохранять предметы в инвентаре

Общие вопросы о Unity3D

Не получается сохранять предметы в инвентаре

Сообщение Kiryuha161 30 май 2023, 22:43

Добрый день! В юнити не так давно, опыта мало. Пытаюсь сделать так, чтобы от сессии к сессии сохранялись данные инвентаря, а точнее предметов в нём. Не получается. Помогите, пожалуйста. Что я делаю не так? Заметил, что json и fliePath не сохраняются. На консоли при дебаге выводит {}
Вот класс с данными
Синтаксис:
Используется csharp
[System.Serializable]
    public class ItemData
    {
        public string Name;
        public int Quantity;
        public int Defence;
        public ItemData(string name, int quantity, int defence)
        {
            this.Name = name;
            this.Quantity = quantity;
            this.Defence = defence;
        }
    }

Вот класс с предметами, который надо добавлять в инвентарь
Синтаксис:
Используется csharp
public class Items : MonoBehaviour
{
    public int[] DefenceItems = new int[] { 5, 10, 15, 20, 25 };
    public bool[] HasItems = new bool[] { false, false, false, false, false };
    public string[] NameItems = new string[] { "Bandit Pants", "Bulletproof cloak", "Bulletproof cloak Elbow", "Bulletproof cloak wrist", "Military Helmet" };
    public int[] Quantity = new int[] { 0, 0, 0, 0, 0 };
 
    public GameObject Character;
    public Sprite[] Sprites;
    public ItemData ItemDataScript;
 
    [SerializeField] private List<ItemData> items = new List<ItemData>();
 
    private int _currentItem;
    private int _currentDefence;
 
    private void Start()
    {
        LoadItems();
    }
    public void Equip(int index)
    {
        if (HasItems[index])
        {
            _currentItem = index;
            _currentDefence = DefenceItems[_currentItem];
            Character.GetComponent<SpriteRenderer>().sprite = Sprites[_currentItem];
        }
    }
    public void AddItem(int index)
    {
        HasItems[index] = true;
 
        if (HasItems[index])
        {
            Quantity[index]++;
        }
     
        SaveItems();//
    }
 

Сохранение
Синтаксис:
Используется csharp
 
public void SaveItems()
    {
        //List<ItemData> dataList = new List<ItemData>();//
 
        for (int i = 0; i < HasItems.Length; i++)
        {
            if (HasItems[i])
            {
               
                string name = NameItems[i];
             
                int quantity = Quantity[i];
                int defence = DefenceItems[i];
                ItemDataScript = new ItemData(name, quantity, defence);
               
                items.Add(ItemDataScript);
               
string json = JsonUtility.ToJson(items);//
       
     
        File.WriteAllText(Path.Combine(Application.persistentDataPath, "/items.json"), json);
            }
        }
 

Загрузка
Синтаксис:
Используется csharp
items.Clear();
        string filePath = Path.Combine(Application.persistentDataPath, "/items.json");
     
 
        if (File.Exists(filePath))
        {
           
            string json = File.ReadAllText(filePath);
         
     
            items = JsonUtility.FromJson<List<ItemData>>(json);
 
           
            foreach (ItemData data in items)//
            {
                int index = GetIndex(data.Name);
 
                if (index != -1)
                {
                    HasItems[index] = true;
                    SetQuantity(data.Name, data.Quantity);
                    Debug.Log("Ok");
                }
 
                else
                {
                    Debug.Log("fail");
                }
            }
        }
    }

Проверка в методе загрузки при foreach не выводится на консоль.
Kiryuha161
UNец
 
Сообщения: 1
Зарегистрирован: 30 май 2023, 22:31

Re: Не получается сохранять предметы в инвентаре

Сообщение 1max1 01 июн 2023, 03:43

https://docs.unity3d.com/ScriptReferenc ... oJson.html

Similarly, passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none). To serialize the actual content of an array or primitive type, it is necessary to wrap it in a class or struct.
Аватара пользователя
1max1
Адепт
 
Сообщения: 5505
Зарегистрирован: 28 июн 2017, 10:51

Re: Не получается сохранять предметы в инвентаре

Сообщение Jarico 02 июн 2023, 16:23

JsonUtility не может напрямую сохранять список или массив нужен контейнер
Синтаксис:
Используется csharp

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

public static class JsonUtilityEx
{
    public static T[] ArrayFromJson<T>(string json)
    {
        ArrayWrapper<T> wrapper = JsonUtility.FromJson<ArrayWrapper<T>>(json);
        return wrapper.Array;
    }

    public static string ToJson<T>(T[] array)
    {
        ArrayWrapper<T> wrapper = new ArrayWrapper<T>();
        wrapper.Array = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        ArrayWrapper<T> wrapper = new ArrayWrapper<T>();
        wrapper.Array = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private struct ArrayWrapper<T>
    {
        public T[] Array;
    }


    public static List<T> ListFromJson<T>(string json)
    {
        ListWrapper<T> wrapper = JsonUtility.FromJson<ListWrapper<T>>(json);
        return wrapper.List;
    }

    public static string ToJson<T>(List<T> array)
    {
        ListWrapper<T> wrapper = new ListWrapper<T>();
        wrapper.List = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(List<T> array, bool prettyPrint)
    {
        ListWrapper<T> wrapper = new ListWrapper<T>();
        wrapper.List = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private struct ListWrapper<T>
    {
        public List<T> List;
    }
}

 
Github: _https://github.com/redheadgektor
Discord: Конь! Чаю!#9382 (сижу редко)
YouTube: _https://www.youtube.com/channel/UCPQ04Xpbbw2uGc1gsZtO3HQ
Telegram: _https://t.me/redheadgektor
Аватара пользователя
Jarico
Адепт
 
Сообщения: 1084
Зарегистрирован: 06 янв 2019, 17:37
Откуда: 0xDEAD
Skype: none
  • Сайт


Вернуться в Общие вопросы

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 16