我正在尝试使用Unity 2018中的二进制格式化程序将整数数组保存到.dat文件。
load函数可以正常工作,但是保存数组会产生异常
用于保存和加载数据的代码:
for loop
构造函数类:
passing the input to your API
这是我保存数据的代码块。我只是在编写用于保存功能的代码行:
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class encryptAndDecrypt : MonoBehaviour
{
private static encryptAndDecrypt instance ;
private string DATA_PATH = "/AnsweredData.dat";
private answeredData myData;
public int hasAnswered;
void Start()
{
instance = this;
}
public void saveData(int[] value)
{
FileStream file = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
file = File.Create(Application.persistentDataPath + DATA_PATH);
answeredData ad = new answeredData(value);
bf.Serialize(file, ad);
print("data Saved");
}
catch (Exception e)
{
if (e != null)
{
// handle exception
Debug.Log(e.ToString());
}
}
finally
{
if (file != null)
{
file.Close();
}
}
}
public void loadData(int location)
{
FileStream file = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
file = File.Open(Application.persistentDataPath + DATA_PATH, FileMode.Open);
myData = bf.Deserialize(file) as answeredData;
Debug.Log("Load Complete");
hasAnswered = myData.HasAnswered[location];
}
catch (Exception e)
{
if (e != null)
{
// handle exception
}
}
}
}
但是当我运行游戏并尝试将数据保存到索引2或任何其他索引时,出现以下异常:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class answeredData {
private int[] hasAnswered = new int[999];
// Empty constructor
public answeredData() { }
// Constructor to take data
public answeredData(int[] _hasAnswered)
{
hasAnswered = _hasAnswered;
}
// Public accessor to access values
public int[] HasAnswered
{
get
{
return hasAnswered;
}
set
{
hasAnswered = value;
}
}
}