我的 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 );
}
}
}
有谁知道这是否可以做到,如果可以怎么办?
告诉您的客户是谁
请注意,移动设备当前不支持 Unity WebGL 内容 设备
Unity Docs
。他们想要的东西是不可能的。对于少数可以正常工作的设备,性能很可能会受到影响,并且大多数功能将无法按预期工作。
Application.PersistentDataPath
实现通用保存/加载解决方案,数据将保存在位置 /idbfs/<md5 hash of data path>
。它将允许数据在多个会话中保持不变。它可能适用于移动设备,但再次强烈建议您不要这样做。如果你想要手机游戏,那就制作手机游戏。另一种选择是不使用 Unity。
将 webGL 游戏转换为应用程序将是有益的,因为在移动浏览器上玩游戏很慢并且用户可能会收到输入延迟。
您可以从 C# 调用 javascript 函数,例如为了使用本地存储。您必须将它们(脚本)添加到扩展名为 .jslib 的“Plugins”文件夹中。更多详细信息请参见:Unity 文档。 我尚未在移动设备上对此进行测试,但我认为没有理由这不起作用。
男人要省去痛苦,就用 playfab 吧
面临类似的问题。我找到了一个奇怪的解决方案。如果保存数据然后重新加载场景,则会保存进度。但是,如果您保存进度并且不重新加载场景,然后在浏览器中重新加载页面,则进度将不会被保存。这一切都是为了在设备上本地保存进度。不过,如果你把进度保存到服务器上,那就不会出现这种奇怪的行为了