Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Unity中实现浏览器保存_C#_Unity3d_Save - Fatal编程技术网

C# 如何在Unity中实现浏览器保存

C# 如何在Unity中实现浏览器保存,c#,unity3d,save,C#,Unity3d,Save,我不知道如何保存在线游戏的数据,但我已经在桌面应用程序中实现了保存。 如何在浏览器上玩的Unity游戏中保存修改后的数据,以便加载数据以恢复原始状态? 我已经有一个保存系统脚本:- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.T

我不知道如何保存在线游戏的数据,但我已经在桌面应用程序中实现了保存。 如何在浏览器上玩的Unity游戏中保存修改后的数据,以便加载数据以恢复原始状态? 我已经有一个保存系统脚本:-

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace GameDevTV.Saving
{
    /// <summary>
    /// This component provides the interface to the saving system. It provides
    /// methods to save and restore a scene.
    ///
    /// This component should be created once and shared between all subsequent scenes.
    /// </summary>
    public class SavingSystem : MonoBehaviour
    {
        /// <summary>
        /// Will load the last scene that was saved and restore the state. This
        /// must be run as a coroutine.
        /// </summary>
        /// <param name="saveFile">The save file to consult for loading.</param>
        private void Update()
        {

        }

        public IEnumerator LoadLastScene(string saveFile)
        {
            Dictionary<string, object> state = LoadFile(saveFile);
            int buildIndex = SceneManager.GetActiveScene().buildIndex;
            if (state.ContainsKey("lastSceneBuildIndex"))
            {
                buildIndex = (int)state["lastSceneBuildIndex"];
            }
            yield return SceneManager.LoadSceneAsync(buildIndex);
            RestoreState(state);
        }

        /// <summary>
        /// Save the current scene to the provided save file.
        /// </summary>
        public void Save(string saveFile)
        {
            Dictionary<string, object> state = LoadFile(saveFile);
            CaptureState(state);
            SaveFile(saveFile, state);
        }

        /// <summary>
        /// Delete the state in the given save file.
        /// </summary>
        public void Delete(string saveFile)
        {
            File.Delete(GetPathFromSaveFile(saveFile));
        }

        // PRIVATE

        private void Load(string saveFile)
        {
            RestoreState(LoadFile(saveFile));
        }

        private Dictionary<string, object> LoadFile(string saveFile)
        {
            string path = GetPathFromSaveFile(saveFile);
            if (!File.Exists(path))
            {
                return new Dictionary<string, object>();
            }
            using (FileStream stream = File.Open(path, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return (Dictionary<string, object>)formatter.Deserialize(stream);
            }
        }

        private void SaveFile(string saveFile, object state)
        {
            PlayerPrefs.Save();
            string path = GetPathFromSaveFile(saveFile);
            print("Saving to " + path);
            using (FileStream stream = File.Open(path, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, state);
            }
        }

        private void CaptureState(Dictionary<string, object> state)
        {
            foreach (SaveableEntity saveable in FindObjectsOfType<SaveableEntity>())
            {
                state[saveable.GetUniqueIdentifier()] = saveable.CaptureState();
            }

            state["lastSceneBuildIndex"] = SceneManager.GetActiveScene().buildIndex;
        }

        private void RestoreState(Dictionary<string, object> state)
        {
            foreach (SaveableEntity saveable in FindObjectsOfType<SaveableEntity>())
            {
                string id = saveable.GetUniqueIdentifier();
                if (state.ContainsKey(id))
                {
                    saveable.RestoreState(state[id]);
                }
            }
        }

        private string GetPathFromSaveFile(string saveFile)
        {
            return Path.Combine(Application.persistentDataPath, saveFile + ".sav");
        }
    }
}
使用系统;
使用系统集合;
使用System.Collections.Generic;
使用System.IO;
使用System.Runtime.Serialization.Formatters.Binary;
使用系统文本;
使用UnityEngine;
使用UnityEngine.SceneManagement;
名称空间GameDevTV.Saving
{
/// 
///此组件提供保存系统的接口。它提供
///保存和恢复场景的方法。
///
///此组件应创建一次,并在所有后续场景之间共享。
/// 
公共阶级储蓄制度:单一行为
{
/// 
///将加载上次保存的场景并恢复状态。此
///必须作为协同程序运行。
/// 
///要查看以进行加载的保存文件。
私有void更新()
{
}
公共IEnumerator LoadLastScene(字符串保存文件)
{
字典状态=加载文件(保存文件);
int buildIndex=SceneManager.GetActiveScene().buildIndex;
if(state.ContainsKey(“lastSceneBuildIndex”))
{
buildIndex=(int)状态[“lastSceneBuildIndex”];
}
收益返回场景管理器。LoadSceneAsync(buildIndex);
恢复不动产(国家);
}
/// 
///将当前场景保存到提供的保存文件中。
/// 
公共void保存(字符串保存文件)
{
字典状态=加载文件(保存文件);
CaptureState(州);
SaveFile(SaveFile,state);
}
/// 
///删除给定保存文件中的状态。
/// 
公共作废删除(字符串保存文件)
{
Delete(GetPathFromSaveFile(saveFile));
}
//私人的
私有无效加载(字符串保存文件)
{
RestoreState(加载文件(保存文件));
}
专用字典加载文件(字符串保存文件)
{
字符串路径=GetPathFromSaveFile(saveFile);
如果(!File.Exists(path))
{
返回新字典();
}
使用(FileStream-stream=File.Open(路径,FileMode.Open))
{
BinaryFormatter formatter=新的BinaryFormatter();
返回(字典)格式化程序。反序列化(流);
}
}
私有void SaveFile(字符串SaveFile,对象状态)
{
PlayerPrefs.Save();
字符串路径=GetPathFromSaveFile(saveFile);
打印(“保存到”+路径);
使用(FileStream-stream=File.Open(路径,FileMode.Create))
{
BinaryFormatter formatter=新的BinaryFormatter();
序列化(流、状态);
}
}
私有无效CaptureState(字典状态)
{
foreach(可保存在FindObjectSoftType()中的SaveableEntity)
{
状态[saveable.GetUniqueIdentifier()]=saveable.CaptureState();
}
状态[“lastSceneBuildIndex”]=SceneManager.GetActiveScene().buildIndex;
}
私有财产(字典状态)
{
foreach(可保存在FindObjectSoftType()中的SaveableEntity)
{
string id=saveable.GetUniqueIdentifier();
if(state.ContainsKey(id))
{
可保存。可恢复的不动产(状态[id]);
}
}
}
私有字符串GetPathFromSaveFile(字符串saveFile)
{
返回Path.Combine(Application.persistentDataPath,saveFile+“.sav”);
}
}
}
当前的保存系统可以保存到桌面位置,但我不确定在线运行的游戏是否可以保存到桌面?
关于如何修改此代码以使其从浏览器中保存,您有什么建议吗?

我相信您可以将所有内容保存在浏览器缓存中,但用户可能会错误地将其删除(我从来没有这样做过)
实际上,我要做的是将数据保存在外部数据库中,托管在某个地方。如果游戏在线,可能需要身份验证,这将允许您区分从谁那里保存的内容

可能还有其他选择,但我还没有真正弄乱Unity中的浏览器游戏。

一种简单但不太可靠的方法是将其存储在持久数据路径中。请注意,此进程不会立即刷新到IndexedDB,您应该使用:Application.ExternalEval(“_JS_FileSystem_Sync()”)

另一种可能的解决方案如下: 您应该将最终保存的数据生成为字符串,一种方法是使用。您应该有一个服务器和一种登录系统来识别用户,然后可以使用PHP将该用户的保存数据字符串关联到数据库中。

第二种解决方案稍微复杂一点,但它确实是我所能想到的WebGL最健壮的解决方案之一。您有多个网站提供这些服务,如1和1。
如果您更愿意尝试第一个免费的替代方案,您可以使用像000webhost这样的网站来存储您的webgGL应用程序+所有PHP功能+数据库来存储信息。

通常,您可以使用例如
JSON
XML
或自定义序列化。然后请注意
WebGL:Application.persistentDataPath指向/idbfs/,其中数据路径是除去所有内容的URL,包括任何“?”组件之前的最后一个“/”和之后的内容。
因此它可能会起作用。。。你试过了吗?