2016-12-05 148 views
6

我发现在Unity3D游戏引擎中保存游戏数据的最佳方式。
起初,我使用BinaryFormatter序列化对象。什么是保存游戏状态的最佳方式?

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

在我的情况下,保存格式必须是字节数组。

+0

为什么一定要你的格式是一个字节数组?为什么不把它保存到PlayerPrefs? –

+1

使用序列化有什么问题? –

回答

20

但我听说这种方式有一些问题,不适合保存。

没错。在某些设备上,存在BinaryFormatter的问题。更新或更改课程时会变得更糟。由于类不再匹配,您的旧设置可能会丢失。有时,您在阅读保存的数据时会遇到异常。

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

保存的最佳方法是使用PlayerPrefsJson。你可以学习如何做到这一点here

在我的情况下,保存格式必须是字节数组

在这种情况下,你可以将其转换成JSON然后转换成JSON stringbyte阵列。然后您可以使用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; 
    } 
} 

USAGE

实施例类保存

[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"); 
+0

谢谢! 因为我们的项目需要mono2x设置,所以我们的环境设置失败了。 我会尝试JsonUtility和您的评论! – Sizzling

相关问题