【问题标题】:Save a list of shop Items and load it in unity保存商店物品列表并统一加载
【发布时间】:2021-10-15 19:11:22
【问题描述】:

在下面的脚本中,我每次购买发生 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");
        }
    }
}

【问题讨论】:

    标签: c# unity3d save load


    【解决方案1】:

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

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

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

    “Serializable”属性很重要,因为我们需要“Serialize”这些数据。 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"
    }
    

    【讨论】:

    • 您好,谢谢。但我不明白如何保存数据。我不明白那部分。根据我的脚本,我在检查器和 onButtonClickFunction 外部分配游戏对象,我们检查钱,如果是,我们购买。那么我应该在购买函数中传递 saveData json 函数吗
    • 或者保存数据不断保存我拥有的shopItem类并自行加载和赋值。无法理解这部分。很抱歉第一次查看 json。了解保存和检索文件
    • 嘿,我已经用我尝试你的版本更新了这个问题,但我无法让它首先工作我的商店不工作,其次没有在 dataPath 中创建文件。 @安东。你能检查一下并告诉我我哪里做错了。我用名称更新代码突出显示了代码。非常感谢您的帮助
    • 嘿,很好地实现它:) 据我所知,您只错过了一件事。在开始加载数据时,您需要将其分配给 myShopDataList。然后检查它是否为空。如果是创建 ShopDataList 的新实例: myShopData = LoadMyData(Application.dataPath + "/ShopItems.json"); if(myShopData == null) { myShopData = new ShopDataLis(); myShopData.ShopItemData = new List();// 或者你初始化你的数组/列表} 这应该在没有保存文件时处理初始状态
    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2017-10-14
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2012-11-03
    相关资源
    最近更新 更多