如何使用二进制c#保存库存



我一直在努力保存我的库存。我的清单脚本运行得很好,但当我想将其保存到二进制文件时,它不会保存。我不知道为什么这个代码不起作用。你能帮我吗?

这是我的库存代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SimpleInventory
{
[System.Serializable]
public class Inventory : MonoBehaviour
{
[Header("InventoryUI")]
[SerializeField] private UI.InventoryUI inventoryUI = null;
private Dictionary<Item, int> inventory = new Dictionary<Item, int>();
public Dictionary<Item, int> GetInventory => inventory;
public int NumUniqueItems => inventory.Count;
public delegate void OnInventoryChange();
public OnInventoryChange onInventoryChange;
public delegate void OnAddNewItem(Item item, int count);
public OnAddNewItem onAddNewItem;
public Text additemtext;
private void Start()
{
if (inventoryUI)
inventoryUI.InitializeUI(this);
additemtext.enabled = false;
}
public void AddToInventory(Item item, int count = 1)
{
if (!inventory.ContainsKey(item))
inventory.Add(item, count);
else
inventory[item] += count;
Debug.Log($"Added { count} of { item.name} to the inventory");
StartCoroutine(itemTextnum());
additemtext.text = "+ " + count + " "+ item.name + " collected";
onInventoryChange?.Invoke();
}
public void RemoveFromInventory(Item item, int count) // item satma,
{
if (!inventory.ContainsKey(item))
throw new System.Exception("the dictionary does not contain that item");
if (inventory[item] >= count)
{
inventory[item] -= 1;
Debug.Log("count" + count);
}
else
{
Debug.Log("count to zero");
inventory[item] = 0;
}
onInventoryChange?.Invoke();
}

IEnumerator itemTextnum()
{
additemtext.enabled = true;
yield return new WaitForSeconds(1f);
additemtext.enabled = false;
}
}
}

这里是二进制:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
namespace SimpleInventory
{
public class SaveManager
{
private Inventory inv;    // the Dictionary used to save and load data to/from disk
protected string savePath;
public SaveManager()
{
this.savePath = Application.persistentDataPath + "/inventory.inv";
this.inv = new Inventory();
this.loadDataFromDisk();
}
/**
* Saves the save data to the disk
*/
public void saveDataToDisk()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(savePath);
bf.Serialize(file, inv);
file.Close();
}
/**
* Loads the save data from the disk
*/
public void loadDataFromDisk()
{
if (File.Exists(savePath))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(savePath, FileMode.Open);
this.inv = (Inventory)bf.Deserialize(file);
file.Close();
}
}
}
}

我的清单脚本运行得很好,但当我想将其保存到二进制文件时,它不会保存。我不知道为什么这个代码不起作用。你能帮我吗?

我添加了我的inventoryUI代码,我认为我应该尝试保存的脚本:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;

namespace SimpleInventory
{

public class InventoryUI : MonoBehaviour
{
private Inventory inventory = null;
[SerializeField] int numSlotstoCreate = 15;

[SerializeField] ItemSlotUI[] itemSlots = null;
[SerializeField]  GameObject slotUIPrefab = null;
[SerializeField]  private Transform contentParent = null;
public GameObject inventoryAcma;
public GameObject envanterarka;

public string savePath = "/Inventory.save";
public void Start()
{
inventoryAcma.SetActive(false);
envanterarka.SetActive(false);


}

public void Update()
{

}
/*
public void Save()
{
string saveData = JsonUtility.ToJson(this, true);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(string.Concat(Application.persistentDataPath, savePath));
bf.Serialize(file, saveData);
file.Close();

}
public void Load()
{
if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(string.Concat(Application.persistentDataPath, savePath), FileMode.Open);
JsonUtility.FromJsonOverwrite(bf.Deserialize(file).ToString(), this);
file.Close();
}
}
*/
public void InitializeUI(Inventory inventory)
{
this.inventory = inventory;
CreateItemSlots();
UpdateItemSlots();

inventory.onInventoryChange += UpdateItemSlots;
}

public void CreateItemSlots()
{
itemSlots = new ItemSlotUI[numSlotstoCreate];




for (int i = 0; i < numSlotstoCreate; i++)
{


GameObject obj = Instantiate(slotUIPrefab);
obj.transform.SetParent(contentParent.transform,false);
itemSlots[i] = obj.GetComponent<ItemSlotUI>();

}

}

private void UpdateItemSlots()
{
int i = 0;

foreach (KeyValuePair<Item, int> kvp in inventory.GetInventory)
{
if (kvp.Value == 0)
itemSlots[i].gameObject.SetActive(false);
else
{
itemSlots[i].gameObject.SetActive(true);
itemSlots[i].UpdateSlotUI(this, kvp.Key, kvp.Value);


}
i++;
}

for (int j = i; j < itemSlots.Length; j++)
{

itemSlots[j].gameObject.SetActive(false);
}

}







public void itemClicked(Item item)
{
inventory.RemoveFromInventory(item, 1);
}
public void InventoryAcmaButton()
{
inventoryAcma.SetActive(true);
envanterarka.SetActive(true);
}
public void InventoryKapamaButton()
{
inventoryAcma.SetActive(false);
envanterarka.SetActive(false);
}




}

}

尝试使用"使用语句";。你可以阅读关于";使用语句";通过此链接:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

static void BinarySerialize(dynamic database)
{
var bf = new BinaryFormatter();
using (var fs = new FileStream("file.bin", FileMode.OpenOrCreate))
{
bf.Serialize(fs, database);
}
}
static void BinaryDeserialize(out dynamic database)
{
var bf = new BinaryFormatter();
using (var fs = new FileStream("file.bin", FileMode.OpenOrCreate))
{
database = bf.Deserialize(fs) as Inventory[];
}
}

最新更新