【发布时间】: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");
}
}
}
【问题讨论】: