Search Unity

A simple Save/Load data ?

Discussion in 'Immediate Mode GUI (IMGUI)' started by orangethekid, Sep 19, 2017.

  1. orangethekid

    orangethekid

    Joined:
    Sep 19, 2017
    Posts:
    2
    Hi, there
    i'd like to make a creation tool for my project.
    it's a simple [save/load/edit] a data file.

    Code (CSharp):
    1. [System.Serializable]
    2. public class Character{
    3.    public int id;
    4.    public string name;
    5. }
    Code (CSharp):
    1. public class Character_Create:EditorWindow{
    2.   private List<Character> data = new List<Characer>();
    3.   private Character input = new Character();
    4.  
    5.   void OnGUI(){
    6.    input.id = EditorGUILayout.IntField ("Character ID", input.id);
    7.    input.name = EditorGUILayout.TextField ("Character Name", input.name);
    8.  
    9.    if(GUILayout.Button("Create")){
    10.      data.Add(input);
    11.    }
    12.   }
    13. }
    this is my problem.
    1)Is there easy way to save/load a List<> in to a file.
    and any function to search a member of List<> by using ID to reference ?
    2)what if i use Stream Read/Writer on other platform such a android ?

    or any idea that can make it easier to build a Database file.
    Thankyou.
     
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,618
  3. orangethekid

    orangethekid

    Joined:
    Sep 19, 2017
    Posts:
    2
    i try this.
    Code (CSharp):
    1. if(GUILayout.Button("Create",GUILayout.Height(20))){
    2.             chaDatabase.Add (cha);
    3.             data = JsonUtility.ToJson (chaDatabase);
    4.             MonoBehaviour.print (data);
    5.             System.IO.File.WriteAllText ("Assets/Script/Database/Character", data);
    6.         }
    My List<Character> is not empty. but when i use 'data = JsonUtility.ToJson (chaDatabase);'
    the print out is "{ }"
     
  4. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,618
  5. samizzo

    samizzo

    Joined:
    Sep 7, 2011
    Posts:
    487
    You need to wrap the list in a class, for example:

    Code (csharp):
    1. [Serializable]
    2. public class CharacterList
    3. {
    4.     public List<Character> Characters = new List<Character>();
    5. }
    Then to serialise to JSON:

    Code (csharp):
    1. characterList = new CharacterList();
    2. characterList.Add(character);
    3. json = JsonUtility.ToJson(characterList);
    -sam