[Unity][存檔][JSONUnity]存儲讀取方塊數據

 

 

打包封裝EXE文件後,運行EXE文件後,是可以正常的存儲數據,讀取數據。

第一次打開EXE文件

 

再次打開EXE文件

 


 



在執行保存,讀取方塊 內的數據後,爲什麼會顯示爲


jsonStringZ:{"Items":[{"instanceID":151226},{"instanceID":151256},{"instanceID":151308}]}
UnityEngine.Debug:Log(Object)
JSONDemon:loadJSONCubeDate() (。。。/JSONDemon.cs:99)
UnityEngine.EventSystems.EventSystem:Update()

 

關於上面的解釋,放在在相關資料2裏面的JsonHelper.cs 的註釋中

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)//在.JSON格式存檔文件中讀取 泛類型數組 wrapper
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)//把要保存的數據以數組的形式保存在.JSON格式存檔文件中
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);//JsonUtility在using UnityEngine中有使用
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);//使得 數組數據轉換爲JSON數據
    }

    [System.Serializable]//
    private class Wrapper<T>
    {
        public T[] Items;//泛類型T的數組,名字叫做Items。
    }
}

 

因爲 

...

    [System.Serializable]//
    private class Wrapper<T>
    {
        public T[] Items;//泛類型T的數組,名字叫做Items。//如果把這裏的Items改爲其他的例如:Avaters,那麼對應的Items也要改爲Avaters,當 在本文的例子當中,保存,讀取數據的時候,就會顯示的Debug.log爲jsonStringZ:{"Avaters":[{"instanceID":151226},{"instanceID":151256},{"instanceID":151308}]}
    }

如果把這裏的Items改爲其他的例如:Avaters,那麼對應的Items也要改爲Avaters,當 在本文的例子當中,保存,讀取數據的時候,就會顯示的Debug.log爲

jsonStringZ:{"Avaters":[{"instanceID":151226},{"instanceID":151256},{"instanceID":151308}]}

 

 

在using  UnityEngine;

namespace UnityEngine中ToJson函數的解釋,使得 數據轉換爲JSON數據

 //
        // 摘要:
        //     Generate a JSON representation of the public fields of an object.
        //
        // 參數:
        //   obj:
        //     The object to convert to JSON form.
        //
        //   prettyPrint:
        //     If true, format the output for readability. If false, format the output for minimum
        //     size. Default is false.
        //
        // 返回結果:
        //     The object's data in JSON format.
        public static string ToJson(object obj);
        //
        // 摘要:
        //     Generate a JSON representation of the public fields of an object.
        //
        // 參數:
        //   obj:
        //     The object to convert to JSON form.
        //
        //   prettyPrint:
        //     If true, format the output for readability. If false, format the output for minimum
        //     size. Default is false.
        //
        // 返回結果:
        //     The object's data in JSON format.
        public static string ToJson(object obj, bool prettyPrint);

 


Test_JSONCube.cs

using UnityEngine;

[System.Serializable]//
public class Test_JSONCube : MonoBehaviour {

    /// <summary>
    /// world position
    /// </summary>
    public Vector3 position;
    /// <summary>
    /// rotation
    /// </summary>
    public Quaternion quaternion;
    
    /// <summary>
    /// 場景生成的固定的ID
    /// </summary>
    public int instanceID;
    public string Name;
    public int Level;
    public int[] Stats;

    /// <summary>
    /// 當進行 存檔 的時候,對方塊 的數據 進行 設置
    /// </summary>
    public void StartCube()
    {
        instanceID = this.GetInstanceID();
        //Quaternion rot = this.transform.rotation;
        position = this.transform.position;
        //rotation = new Vector3(rot.x, rot.y, rot.z);
        quaternion = this.transform.rotation;
    }//StartCube

    /// <summary>
    /// 讀檔的時候,對方塊進行的設置
    /// </summary>
    /// <param name="jSONCube"></param>
    public void setCube(Test_JSONCube jSONCube)
    {
        if (Name == jSONCube.Name)//進行比較判斷,通過 名字 的不同 用於區分 紅、綠、藍 ,三種不同的方塊,
        {
            this.transform.position = jSONCube.position;//加上一個值用於區分,存檔方塊 和 讀檔方塊的不同
            this.transform.rotation = jSONCube.quaternion;
            //Name = jSONCube.Name;
            Level = jSONCube.Level;
            Stats = jSONCube.Stats;
            this.transform.position += new Vector3(0,2,0);//加上一個值用於區分,存檔方塊 和 讀檔方塊的不同
        }//if
    }//setCube
}//Test_JSONCube

JSONDemon.cs(需要相關資料2 的JsonHelper.cs保存在項目工程文件夾內)


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Linq;//.OfType


public class JSONDemon : MonoBehaviour {

    /// <summary>
    /// 部分存檔文件路徑
    /// </summary>
    string path_json = "/123/Scene/Test_Scene/Test_JSON/SaveData.json";
    /// <summary>
    /// 完整的 存檔文件路徑
    /// </summary>
    string path;
    /// <summary>
    /// 讀取的JSON文本內容
    /// </summary>
    string jsonString;
    /// <summary>
    /// Test_JSONCube數組
    /// </summary>
    public Test_JSONCube[] test_JSONCubes;

    /// <summary>
    /// Test_JSONCube數組
    /// 讀取 存儲數據的 方塊,更新座標,rotation
    /// </summary>
    public Test_JSONCube[] test_JSONCubes_LoadCube;

    public Text text;

    private void Start()
    {
        foreach (Test_JSONCube cube in test_JSONCubes)
        {
            cube.StartCube();
        }
        //saveJSONCubeData();
        //loadJSONCubeDate();
    }

    /// <summary>
    /// 保存JSON數據
    /// </summary>
    public void saveJSONCubeData()
    {
        DataJSONFile();
        //獲得 存檔.json 的文件路徑
        path = Application.dataPath + path_json;
        string jsonStringZ = File.ReadAllText(path);//讀取 存檔文件.json的 所有文本內容,以String變量的形式讀取

        List<Test_JSONCube> saveListData = new List<Test_JSONCube>();
        /*foreach (Test_JSONCube jSONCube in test_JSONCubes)
        {
            saveListData.Add(jSONCube);
        }*///或者saveListData.AddRange(test_JSONCubes);
        saveListData.AddRange(test_JSONCubes);//或者foreach (Test_JSONCube jSONCube in test_JSONCubes)


        string jsonToSave = JsonHelper.ToJson(saveListData.ToArray());
        File.WriteAllText(Application.dataPath + path_json, jsonToSave);
        //PlayerPrefs.SetString("Data", jsonToSave);
        //PlayerPrefs.Save();//保存在 PlayerPrefs.Save() 本地化保存數據

        if (text != null)
        {
            text.text = "SAVE COMPLETE";
        }
        
    }//saveJSONCubeData()

    /// <summary>
    /// 讀取JSON數據
    /// </summary>
    public void loadJSONCubeDate()
    {
        //DataJSONFile();

        if (File.Exists(Application.dataPath + path_json) == true)
        {
            //獲得 存檔.json 的文件路徑
            path = Application.dataPath + path_json;
            string jsonToLoad = File.ReadAllText(path);//讀取 存檔文件.json的 所有文本內容,以String變量的形式讀取
            Debug.Log("jsonStringZ:"+ jsonToLoad);
            if (jsonToLoad != ""
                && test_JSONCubes_LoadCube.Length > 0)//用一個完全空白的empty.json文件進行測試,爲了使得 獲取的 文本內容不爲空
            {

                //Load as Array
                Test_JSONCube[] _tempLoadListDataZ = JsonHelper.FromJson<Test_JSONCube>(jsonToLoad);
                //Convert to List
                List<Test_JSONCube> loadListDataZ = _tempLoadListDataZ.OfType<Test_JSONCube>().ToList();

                Debug.Log("-----------------------");
                foreach (Test_JSONCube cube in loadListDataZ)
                {
                    Debug.Log("cubeName:"+ cube.Name+"/Level:"+ cube.Level+"/Position:"+ cube.position+"/Rotation:"+ cube.quaternion);

                    for (int i = 0; i < loadListDataZ.Count; i++)
                    {
                        test_JSONCubes_LoadCube[i].setCube(cube);
                    }
                }
                for (int i = 0; i < loadListDataZ.Count ;i++)
                {
                    //test_JSONCubes_LoadCube[i];
                }

                Debug.Log("-----------------------");
                //Debug.Log("   loadListDataZ length: " + loadListDataZ.Count);
            }

        }


        if (text != null)
        {
            text.text = "LOAD COMPLETE";
        }
    }//loadJSONCubeDate()

    /// <summary>
    /// 判斷 保存的JSON 格式的空文本文件 是否存在,如果存在 就 複製粘貼 爲新的存檔文件。
    /// </summary>
    private void DataJSONFile()// [Unity][File][JSON]file.copy的使用方法代碼動態創建.json文件
    {
        if (File.Exists(Application.dataPath + "/Resources/empty.json") == true
            && File.Exists(Application.dataPath + path_json) == false)
        {
            File.Copy(Application.dataPath + "/Resources/empty.json", Application.dataPath + path_json);
        }
    }//DataJSONFile()

}//JSONDemon

問題

當SaveData.json中已經保存了數據,當直接在Start函數中使用 loadJSONCubeDate();讀取SaveData.json的數據的時候,發現不能產生正常的結果,無法讀取數據的內容。

SaveData.json

{"Items":[{"instanceID":151226},{"instanceID":151256},{"instanceID":151308}]}

JSONDemon.cs

...
private void Start()
    {
        loadJSONCubeDate();
    }
...

 

解決辦法在相關資料4裏面有詳細的描述。

 


 

打包封裝EXE文件後,相關資料以及出現的問題在 相關資料5

打包封裝EXE文件後,運行EXE文件後,是可以正常的存儲數據,讀取數據。

第一次打開EXE文件

 

再次打開EXE文件

 


相關資料:

1.[Unity][JSON][csv][JSONUnity]csv-JSON如何在CSV文件中保存數組並讀取JSON數組

2.[Unity][JSON][csv][JSONUnity]csv-JSON複雜數據的管理

3.[Unity][存檔][JSONUnity]讀取方塊數據爲什麼只能保存instanceID

4.

[Unity][File][JSON]file.copy的使用方法代碼動態創建.json文件

5.

 

[Unity][EXE][存檔]EXE打包文件代碼動態新建JSON存檔數據以及讀取

6.

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章