通过对音频和纹理数据进行大量优化,我的Unity WebGL游戏可以在移动Web浏览器上运行。在桌面环境下,保存游戏数据运作正常。但是当我在移动浏览器上玩同一款游戏时,似乎没有任何地方保存游戏数据。以下是我本地保存和加载数据的代码。
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class DataAccess
{
[DllImport ( "__Internal" )]
private static extern void SyncFiles ( );
[DllImport ( "__Internal" )]
private static extern void WindowAlert ( string message );
public static void Save ( Stats stats )
{
string dataPath = string.Format ( "{0}/Stats.dat", Application.persistentDataPath );
BinaryFormatter binaryFormatter = new BinaryFormatter ( );
FileStream fileStream;
try
{
if ( File.Exists ( dataPath ) )
{
File.WriteAllText ( dataPath, string.Empty );
fileStream = File.Open ( dataPath, FileMode.Open );
}
else
{
fileStream = File.Create ( dataPath );
}
binaryFormatter.Serialize ( fileStream, stats );
fileStream.Close ( );
if ( Application.platform == RuntimePlatform.WebGLPlayer )
{
SyncFiles ( );
}
}
catch ( Exception e )
{
PlatformSafeMessage ( "Failed to Save: " + e.Message );
}
}
public static Stats Load (Stats stats )
{
//Stats stats = null;
string dataPath = string.Format ( "{0}/Stats.dat", Application.persistentDataPath );
try
{
if ( File.Exists ( dataPath ) )
{
BinaryFormatter binaryFormatter = new BinaryFormatter ( );
FileStream fileStream = File.Open ( dataPath, FileMode.Open );
stats = ( Stats ) binaryFormatter.Deserialize ( fileStream );
fileStream.Close ( );
}
}
catch ( Exception e )
{
PlatformSafeMessage ( "Failed to Load: " + e.Message );
}
return stats;
}
private static void PlatformSafeMessage ( string message )
{
if ( Application.platform == RuntimePlatform.WebGLPlayer )
{
WindowAlert ( message );
}
else
{
Debug.Log ( message );
}
}
}
有人知道这个能做到吗?如果可以,怎么做?