コード例 #1
0
        //save all of our games data in one go.
        public void SaveJson()
        {
            //get the loaded scenes from the scene manager.
            string[] loaded = CustomSceneManager.GetLoadedScenes();
            if (loaded.Length == 0) //if we have no scenes loaded, just set some random ones for testing purposes.
            {
                loaded = new string[] { "hello", "world", "12345Scene" };
            }

            //set up some fake player data to save.
            PlayerSaveData data = new PlayerSaveData()
            {
                loadedScenes = loaded,
                x            = 1,
                y            = 2,
                z            = 5
            };

            //get the JSON string, looks something like this:
//            {
//                "loadedScenes": [
//                    "hello",
//                    "world",
//                    "12345Scene"
//                  ],
//                  "x": 1.0,
//                  "y": 2.0,
//                  "z": 5.0
//              }
            string save = JsonUtility.ToJson(data, true);

            //get the file path. this is at CurrentUser/AppData/LocalLow/Company/Product/saveFile.sf
            //Company and Product are set by us in the Project Settings / Player.
            string filePath = Path.Combine(Application.persistentDataPath, "saveFile.sf");
            //Open the File: Create a new one
            FileStream stream = File.Open(filePath, FileMode.Create);

            //We need a byte array to actually write anything to our FileStream, we get this from standard UTF8 encoding
            //? What is UTF8? https://en.wikipedia.org/wiki/UTF-8
            //! A lot of modern websites use UTF-8 Encoding since it has support for a pretty wide variety of characters :)
            byte[] buffer = Encoding.UTF8.GetBytes(save);

            //Write the entire buffer array to the stream.
            stream.Write(buffer, 0, buffer.Length);

            //Flush the stream. This is essential to "dumping" all the data from the RAM that C# uses into the storage on the harddrive.
            stream.Flush();
            //Dispose the stream, this can be simplified when utilizing a using block: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
            stream.Dispose();
        }