保存商店商品列表并统一加载

Save a list of shop Items and load it in unity

在下面的脚本中,每次我购买发生 OnShopItemBtnClicked 函数的角色时,我都会尝试保存 ShopItemList。我试图用 playerprefs 保存这个但失败了。有没有更好的办法。听说json是一种方法,可以实现这个。但我不知道 json 是什么或如何使用它。有人可以帮助我如何使用当前的商店系统保存和加载东西。求求你,我想了这么多都伤透了脑袋才得到答案

更新代码

[Serializable]
public class ShopItem
{
    public Sprite CharacterImage;
    public GameObject charactersModel;
    public int Price;
    public bool isPurchased = false;
}

//
[Serializable]
public class ShopDataList
{
    public ShopItem[] ShopItemData;
}

public class Shop : MonoBehaviour
{
    ShopDataList myShopDataList = new ShopDataList();
    //public List<ShopItem> ShopItemsList;


    [Space]
    [Header("Item Template & Display")]
    GameObject ItemTemplate;
    GameObject g;
    [SerializeField] Transform ShopScrollView;
    Button buyBtn;


    GameObject getGameManager;
    GameManager GameManagerRef;



    public void SaveMyData(ShopDataList data)
    {
        string jsonString = JsonUtility.ToJson(data); // this will give you the json (i.e serialize the data)
        File.WriteAllText(Application.dataPath + "/ShopItems.json", jsonString); // this will write the json to the specified path
    }

    public ShopDataList LoadMyData(string pathToDataFile)
    {
        if (!File.Exists(pathToDataFile)) return null;

        string jsonString = File.ReadAllText(pathToDataFile); // read the json file from the file system
        ShopDataList myData = JsonUtility.FromJson<ShopDataList>(jsonString); // de-serialize the data to your myData object
        return myData;
    }

    private void Start()
    {
        LoadMyData(Application.dataPath + "/ShopItems.json");

    getGameManager = GameObject.Find("GameManager");
        GameManagerRef = getGameManager.GetComponent<GameManager>();
        ItemTemplate = ShopScrollView.GetChild(0).gameObject;

        var length = myShopDataList.ShopItemData.Length;
        for (int i = 0; i < length; i++)
        {
            g = Instantiate(ItemTemplate, ShopScrollView);
            g.transform.GetChild(0).GetComponent<Image>().sprite = myShopDataList.ShopItemData[i].CharacterImage; //ShopItemsList[i].CharacterImage; //
            g.transform.GetChild(1).GetComponentInChildren<TextMeshProUGUI>().text = myShopDataList.ShopItemData[i].Price.ToString(); //ShopItemsList[i].Price.ToString(); //**
            buyBtn = g.transform.GetChild(2).GetComponent<Button>();
            if (myShopDataList.ShopItemData[i].isPurchased)
            {
                DisableBuyButton();
            }
            buyBtn.AddEventListener(i, OnShopItemBtnClicked);
        }
        Destroy(ItemTemplate);
    }

    public void DisableBuyButton()
    {
        buyBtn.interactable = false;
        buyBtn.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "PURCHASED";

    }



    void OnShopItemBtnClicked(int itemIndex)
    {
        if (GameManagerRef.HasEnoughCoins(myShopDataList.ShopItemData[itemIndex].Price))
        {
            //purchase Item
            GameManagerRef.UseCoins(myShopDataList.ShopItemData[itemIndex].Price);
            myShopDataList.ShopItemData[itemIndex].isPurchased = true;
            buyBtn = ShopScrollView.GetChild(itemIndex).GetChild(2).GetComponent<Button>();
            GameManagerRef.character.Add(myShopDataList.ShopItemData[itemIndex].charactersModel);
            DisableBuyButton();
            SaveMyData(myShopDataList);
        }
        else
        {
            Debug.Log("You dont have sufficient amount");
        }
    }
}

您需要调用 PlayerPrefs.Save() 方法来实际保存您在 PlayerPrefs 中更改的内容。

但你是对的,将内容保存在外部文件中通常是更好的处理方式。 Json 只是一个具有特定语法的文本文件。要将一些数据保存到 Json,您首先必须创建一个 class 来保存数据,例如

[Serializable]
public class MyData
{
    public int level;
    public string charName;
}

“可序列化”属性很重要,因为我们需要“序列化”此数据。 Unity 有一个简单的 json 序列化程序供您使用。这是您必须做的:

public void SaveMyData(MyData data)
{
    string jsonString = JsonUtility.ToJson(data); // this will give you the json (i.e serialize the data)
    File.WriteAllText("Path/file/name.json", jsonString); // this will write the json to the specified path
}

public MyData LoadMyData(string pathToDataFile)
{
    string jsonString = File.ReadAllText(pathToDataFile); // read the json file from the file system
    MyData myData = JsonUtility.FromJson<MyData>(jsonString); // de-serialize the data to your myData object
    return myData;
}

这就是您的 json 文件的样子:

{
    "level":123,
    "charName":"My awesome character"
}