2015年11月30日 星期一

Unity GUI collocation Json and Create text write Date (Unity GUI 搭配 Json和建立文字檔並寫入資訊)

TestOnGUI (C#) : 

using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

// _Book class wait write data
public class _Book {
    public int ID { get; set; }
    public string Name { get; set;}
}

// _BookDate afterwards increase _Book class data
public class _BOOKData {
    public List<_Book> book = new List<_Book>();
}

public class TestOnGUI : MonoBehaviour {

    _Book bookTest;

    void Start() {
        bookTest = new _Book();
    }

    // Input Data value
    string id = "", name = ""; 

    void OnGUI() {

        /**
         * GUI can't dirct designation _Book class parameter, so wording. 
         * Name variable only write in global.
        */
        id = GUI.TextArea(new Rect(Screen.width/Screen.width,Screen.height/Screen.height, 100, 30), id, 200);

        // int to String
        int intId;
        int.TryParse(id, out intId);
        bookTest.ID = intId;

        name = GUI.TextArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height+50f, 100, 30), name, 200);
        bookTest.Name = name;

        if (GUI.Button(new Rect(Screen.width/Screen.width, Screen.height/Screen.height+100, 100, 50),"確定")) {

            // RootLibrary add book class Date
            _BOOKData bookDate = new _BOOKData();
            bookDate.book.Add(bookTest);

            // Json Encoding
            string outPut = JsonConvert.SerializeObject(bookDate);
            print(outPut);

            // Json Decoding
            _BOOKData _lib = JsonConvert.DeserializeObject<_BOOKData>(outPut);

            foreach (_Book book in _lib.book) {
                print("ID" + book.ID);
                print("Name" + book.Name);

                for (int i = 0; i < _lib.book.Count; i++)
                {
                    print("ListDate[" + i + "]:" +_lib.book[i]);
                }
            }

            //Create text file
            string[] createTxtValue = {bookTest.ID.ToString(), bookTest.Name};
            File.WriteAllLines("C:/Users/user/Desktop/AAA.txt", createTxtValue);
        }
    }
}

結果圖:






沒有留言:

張貼留言