如何使可编写脚本的对象在Unity中与持久性数据一起使用

问题描述 投票:-1回答:1

我的目标是创建50个都具有相同结构并使用持久性数据的对象。

我首先了解了持久性数据,然后按照Unity的官方教程进行了工作。由于本教程使用的是一个对象,因此我开始创建游戏,例如:

我保存和加载持久性数据的方法。

 public void saveBuy1()
    {


        Debug.Log("SavingBuy1");

        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/buy1.dat");
        PlayerData data = new PlayerData();







        data.isBoxSold = 1;

        bf.Serialize(file, data);
        file.Close();
    }
public void loadBuy1()
    {
        Debug.Log("loading");



        if (File.Exists(Application.persistentDataPath + "/buy1.dat"))

        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/buy1.dat", FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize(file);
            file.Close();


            GameObject.Find("buyBox1").GetComponentInChildren<Text>().text = "Item bought";
            isBoxsold1 = data.isBoxSold1;

        }
    }

我的PlayerData类:

[Serializable]
class PlayerData {

public int coinsAmount;
public int isBoxsold;

}

创建盒子

 //Regular box 1
    int isBoxSold = 0;
    int price1 = 6;
    public Text boxPrice1;
    public Image boxImage1;
    public Button buyButton1;

但是我很快意识到,创建盒子对象必须比这样做更有效:

 //Regular box 1
    int isBoxSold1 = 0;
    int price1 = 6;
    public Text boxPrice1;
    public Image boxImage1;
    public Button buyButton1;

//Regular box 2
    int isBoxSold2 = 0;
    int price2 = 6;
    public Text boxPrice2;
    public Image boxImage2;
    public Button buyButton2;

然后创建loadBuy1方法的副本,并将其称为loadBuy2等...

因此,我发现了可编写脚本的对象,似乎可以解决必须为每个框创建新属性和字段而只创建一个类的问题。但是我无法理解如何使用具有持久性的可脚本化对象将box类的这些实例连接起来?有没有一种方法可以创建一个加载和保存方法来一次保存和加载所有box对象的所有持久性数据?还是仍然需要为每个框创建保存和加载方法?

c# unity3d persistence
1个回答
0
投票

听起来像您想要的,而不是将每个框的数据存储在适当的ScriptableObject类中。

[CreateAssetMenu]
public class Box : ScriptableObject
{
    // Inspector
    [SerializeField] private int _isBoxSold = 0;
    [SerializeField] private int _price = 6;
    [SerializeField] private Text _boxPrice;
    [SerializeField] private Image _boxImage;
    [SerializeField] private Button _buyButton;

    // Public readonly properties
    public int IsBoxSold => _isBoxSold;
    public int Price => _price;
    public Text BoxPrice => _boxPrice;
}

然后将它们存储为列表

[Serializable]
public class PlayerData 
{
    public int coinsAmount;

    [SerializeField] private List<Box> _boxes;

    // Example: run through all boxes and update their texts
    public void UpdateBoxes()
    {
        foreach(var box in _boxes)
        {
            box.BoxPrice.text = box.Price.ToString();
        }
    }
}

一般说明:

您应该从不+ "\"用于系统路径!而是使用Path.Combine,它会根据目标平台自动使用正确的路径分隔符,例如

Path.Combine
© www.soinside.com 2019 - 2024. All rights reserved.