gpt4 book ai didi

c# - 保存游戏状态的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 18:01:50 24 4
gpt4 key购买 nike

我找到了在 Unity3D 游戏引擎中保存游戏数据的最佳方式。
首先,我使用 BinaryFormatter 序列化对象。

但是听说这种方式存在一些问题,不适合保存。
那么,保存游戏状态的最佳或推荐方法是什么?

在我的例子中,保存格式必须是字节数组。

最佳答案

But I heard this way has some issues and not suitable for save.

没错。在某些设备上,BinaryFormatter 存在问题。当您更新或更改类(class)时,情况会变得更糟。由于类不再匹配,您的旧设置可能会丢失。有时,您会因此在读取保存的数据时遇到异常。

此外,在 iOS 上,您必须添加 Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); 否则您将遇到 BinaryFormatter 问题。

最好的保存方式是使用 PlayerPrefsJson。您可以学习如何做到这一点 here .

In my case, save format must be byte array

在这种情况下,您可以将其转换为 json,然后将 json string 转换为 byte 数组。然后,您可以使用 File.WriteAllBytesFile.ReadAllBytes 来保存和读取字节数组。

这是一个可用于保存数据的通用类。几乎与 this 相同但它使用PlayerPrefs。它使用文件来保存json数据。

DataSaver 类:

public class DataSaver
{
//Save Data
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");

//Convert To Json then to bytes
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);

//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
//Debug.Log(path);

try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}

//Load Data
public static T loadData<T>(string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");

//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}

if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}

//Load saved Json
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}

//Convert to json string
string jsonData = Encoding.ASCII.GetString(jsonByte);

//Convert to Object
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}

public static bool deleteData(string dataFileName)
{
bool success = false;

//Load Data
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");

//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return false;
}

if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return false;
}

try
{
File.Delete(tempPath);
Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
Debug.LogWarning("Failed To Delete Data: " + e.Message);
}

return success;
}
}

用法:

要保存的示例类:

[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}

保存数据:

PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;

//Save data from PlayerInfo to a file named players
DataSaver.saveData(saveData, "players");

加载数据:

PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");
if (loadedData == null)
{
return;
}

//Display loaded Data
Debug.Log("Life: " + loadedData.life);
Debug.Log("High Score: " + loadedData.highScore);

for (int i = 0; i < loadedData.ID.Count; i++)
{
Debug.Log("ID: " + loadedData.ID[i]);
}
for (int i = 0; i < loadedData.Amounts.Count; i++)
{
Debug.Log("Amounts: " + loadedData.Amounts[i]);
}

删除数据:

DataSaver.deleteData("players");

关于c# - 保存游戏状态的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com