[내일 배움 캠프 Unity 4기] W7D4 05.30 TIL

김용준·2024년 5월 30일
0

내일배움캠프

목록 보기
25/47

Goals

  • Special lecture; Serialize

Serialize

  • Definition:
    data would spread memory space. To recreate the object with data, the gathering process was done with byte array. This process is called as Serialize. Today, the data organization for easy access is categorized in Serialize. For the developer, interset set to the serializeation of developer readables.

In Unity, there are some target for serializable methods.

  • PlayerPrefs : to save and load the player data in Unity.
    - e.g)
    public void Serialize()
    {
    	string saveData = <string> + ',' + <string> + ',' + ...
        PlayerPrefs.SetString("PlayerData",saveData); // key, value
    }
    
    public void DeSerialize()
    {
    	string data = PlayerPrefs.GetString("PlayerData");
        string[] datas = data.Split(',');
        
        this.<name> = datas[<name_index>];
    }
    The file locates registry area so that the security level is estimated lower than other methods.
  • CSV(Comma Separated values):
    Advantage comes from the application of Excel. When the file is saved with the format of csv UTF-8, the csv file can be treated as text file format.
    The usage of csv file can be seen in following code snippets
    DataManager || ResourcesManager
    Dictionary<string,List<string>> dialog = new Dictionary<string,List<string>>();
    
    void Start()
    {
    	TextAsset csvData = Resources.Load<TextAsset>("name");
        
        Debug.Log(csvData.text); // print out all data in csv file
        DeSerial(csvData.text.TrimEnd()); // TrimEnd() : remove \r on text
    }
    void DeSerial(string data)
    {
        string[] rowData = csvData.text.Split('\n');
        for(int a=1; a<rowData.Length; a++)
        {
        	string[] colData = csvData.text.Split(',');
            if(dialog.ContainsKey(colData[0])
            {
            	dialog[colData[0]].Add(colData[2])
            }
            else
            {
            	dialog[colData[0]] = new List<string>{colData[2]};
            }
        }    
    }
    public void LoadText(string chapter, int phase)
    {
    	Debug.Log(dialog[chapter][phase]);
    }
    The unique feature is that the elements were separated with , and \n. The adoption of csv format is on the users interest.
  • XML(eXtensible Markup Language):
    To improve the readability, the XML, json, YAML were unveiled. The structure consist with key and value. The format can be seen in the example.
    # header
    <GameData> # root node
    	<PlayerData> # child node
        <nickname> asdf </nickName> # element
        <lv> 9 </lv>
        </PlayerData>
    </GameData>
    		```
    The strict rules is exist. When we write data on XML format, the opener and closer should be attached. Previously, the xml is adopted in many other projects so that the environment was well implemented in Unity. 
    The example usage is 
    ``` cs
    string name;
    int lv;
    int exp;
    
    void CreateXML()
    {
    	XmlDocument xmlDoc = new XmlDocument();
        // environment
        xmlDoc.AppendChild(xmlDoc.createXmlDeclaration("1.0","utf-8","yes"));
        
        // root node
        XmlNode root = xmlDoc.CreateNode(XmlNodeType.Element,"GameData",string.Empty);
        xmlDoc.AppendChild(root);
        
        // child node
        XmlNode child = xmlDoc.CreateNode(XmlNodeType.Element,"PlayerData",string.Empty);
        root.AppendChild(child);
        
        // element 1
        XmlElement nickname = xmlDoc.CreateElement("nickname");
        nickname.InnerText = name;
        child.AppendChild(name);
        // element 2
        XmlElement xmllv = xmlDoc.CreateElement("lv");
        xmllv.InnerText = lv;
        child.AppendChild(xmllv);
        
        
        xmlDoc.Save("./Assets/Resources/GameDatas.xml");
    }
    
    // Deserialize
    void LoadXML()
    {
    	TextAsset t = Resources.Load<TextAsset>(<XML name>);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(t.text);
        
        // Load the node 
        XmlNodeList nodes = xmlDoc.SelectNodes("GameData/PlayerData");
        
        XmlNode playerData = nodes[0];
        
        name = playerData.SelectSingleNode("nickname").InnerText;
        lv = int.Parse(PlayerData.SelectSingleNode("lv").InnerText);
    }
    The xml file was created after a few seconds.
  • JSON
    Currently, the many cases related the file IO, the json is regarded as an default option. Also for the Unity, the Newtonsoft, LitJson and JsonUtility were support the Serialize / DeSerialize process of json file. Among them, In Unity environment, the JsonUtility takes almost 0 seconds which is extremly faster than the Newtonsoft and faster than LitJson. The disadvantage of JsonUtility is that the format is limited. However the special case is the special case. With the JsonUtility we can do almost every tasks relating json.
    Rules of serialize: Link
    The example can be written
    [System.Serializable] // essential to make class serialize on Unity editor
    public class UserData // make class to serialize or deserialize;
    {
    	public string name;
        public int lv;
        public float hp;
        public List<string> friends = new List<string>();
        public List<Inventory> invens = new List<Inventory>();
    }
    [System.Serializable]
    public class Inventory
    {
    	public int size;
        public List<int> itemIds = new List<int>();
    }
    
    //In main class
    {
    	public UserData data;
        private void WhatYouWantToSaveData()
        {
        	var t = JsonUtility.ToJson(data);
            Debug.Log(t);
            File.WriteAllText(Application.persistentDataPath + "\UserData.txt",t);
        }
        
        private void WhatYouWantToLoadData()
        {
        	var t = Fill.ReadAllText(Application.persistentDataPath + "\UserData.txt");
            JsonUtility.FromJson<UserData>(t);
        }
    }
    When the data size is too big to see, there are some external tools to view jsons. And also, same with the whole methods shown, this method is also week at security. To improve that, the encryption and decryption should be studied.
profile
꿈이큰개발자지망생

0개의 댓글