반응형

 

 

유니티를 이용하여 게임을 제작 시 유저의 데이터(점수, 위치)등을 저장해야 하는 경우가 있습니다.

 

그러기 위해서 Json이라는 형식을 이용하면 텍스트로 이루어져 있기 때문에 이해하기도 쉽고, 직렬화 / 역직렬화를 통해  

게임 내 데이터와 Json데이터의 상호 변환이 쉽게 가능합니다.

 

현재 제가 쓰는 2018.3.9 버전에서는 기본적으로 지원하기 때문에 따로 using 할 필요가 없습니다.

 

그럼 바로 실습을 해보겠습니다.

 

JsonTest라는 프로젝트를 하나 만들었습니다.

 

빈 오브젝트를 만듭니다.

 

Add Component를 눌러서 Script를 추가합니다.

스크립트를 더블클릭 합니다.

 

 

 

1. 코드를 확인합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
         
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}
cs

이제 여기서 작업을 하겠습니다.

 

 

 

2. 클래스를 추가합니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
         
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
cs

 

 

 

 

3. 클래스 오브젝트를 생성하고, 데이터를 삽입합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}
cs

 

 

 

 

4. 오브젝트 데이터를 Json형식으로 스트링에 넣습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
        
        Debug.Log("ToJson : " + str); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}
cs

-----------------------------------------------------------------------------------------

 

JsonUtility.ToJson함수를 이용하여 오브젝트를 json형식으로 변환합니다.

다음과 같이 실행됩니다.

 

 

 

5. json형식의 데이터를 다시 오브젝트 형으로 변환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
 
        Debug.Log("ToJson : " + str); 
 
       Data data2 = JsonUtility.FromJson<Data>(str);
        data2.printData(); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
 
 
cs

 

 

 

-----------------------------------------------------------------------------------------

 

JsonUtility.FromJson 함수로 오브젝트로 값을 넣습니다.

 

실행되면 결과는 다음과 같습니다.

 

 

 

 

6. json파일로 저장하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Collections; 
using System.Collections.Generic; 
using System.IO; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
 
        Debug.Log("ToJson : " + str); 
 
       Data data2 = JsonUtility.FromJson<Data>(str);
        data2.printData(); 
 
        // file save 
 
        Data data3 = new Data(); 
        data3.m_nLevel = 99
        data3.m_vecPositon = new Vector3(8.1f, 9.2f, 7.2f); 
 
        
        File.WriteAllText(Application.dataPath + "/TestJson.json", JsonUtility.ToJson(data3)); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}
cs

 

Application.dataPath는 지금 작업 폴더를 말합니다.

실행을 하면 TestJson.json 파일이 생성됩니다.

 

 

 

 

 

7. 저장한 json파일 로드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.Collections; 
using System.Collections.Generic; 
using System.IO; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
 
public class JsonTest : MonoBehaviour 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
 
        Debug.Log("ToJson : " + str); 
 
       Data data2 = JsonUtility.FromJson<Data>(str);
        data2.printData(); 
 
        // file save 
 
        Data data3 = new Data(); 
        data3.m_nLevel = 99
        data3.m_vecPositon = new Vector3(8.1f, 9.2f, 7.2f); 
 
        File.WriteAllText(Application.dataPath + "/TestJson.json", JsonUtility.ToJson(data3)); 
 
        // file load 
 
        string str2 = File.ReadAllText(Application.dataPath + "/TestJson.json"); 
 
       Data data4 = JsonUtility.FromJson<Data>(str2);
        data4.printData(); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}
cs

저장한 파일을 로드합니다.

그 후 콘솔에서 출력합니다.

 

반응형
반응형

C# 직렬화

정의 - 직렬화(Serialization)는 개체(Object)를 저장하거나, 메모리(Memory), 데이터베이스(Database) 또는 파일(File)로 전송하기 위해 개체를
바이트 스트림으로 변환하는 프로세스를 말합니다.

목적 - 저장이나 전송 후 다시 개체로 만들기 위함입니다.

역 프로세스 - 역직렬화(deserialization)로 객체를 재구성합니다.

작동방법 - 개체는 스트림(Stream : 데이터, 패킷, 비트 등의 일련의 연속성을 갖는 흐름을 의미)으로 직렬화되어, 데이터뿐 아니라 버전, 문화권 및 어셈블리 이름과 같은 개체 형식에
대한 데이터를 운반할 수 있습니다. 

직렬화 기법

이진 직렬화(Binary Serialization)
이진 직렬화(Binary Serialization)는 이진 인코딩을 사용하여 저장소(Storage:데이터 저장장치) 또는 소켓 기반 네트워크 스트림과 같은
용도에서 사용할 수 있는 압축된 직렬화(Serialization)를 생성합니다.

XML 직렬화(XML Serialization)
XML 직렬화(XML Serialization)는 개체의 public 필드와 속성 또는 메서드의 매개 변수와 반환 값을 특정 XSD(XML 스키마 정의 언어)
문서와 일치하는 XML 스트림으로 직렬화(Serialization) 합니다.


이진 직렬화(Binary Serialization) 실제 구현

전체 소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // 파일 입출력 스트림을 위해 추가 
using System.Runtime.Serialization.Formatters.Binary; // 바이너리 포맷을 위해 추가 
using System.Runtime.Serialization; // IFormatter 인터페이스 사용을 위해 추가 
 
[Serializable]
public class DataObject
{
    public int num1;
    public int num2;
}
 
namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DataObject data1 = new DataObject();
            data1.num1 = 1;
            data1.num2 = 2;
 
 
            IFormatter formatter = new BinaryFormatter();
 
            Stream streamFileWrite = new FileStream("tttt.txt", FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(streamFileWrite, data1);
            streamFileWrite.Close();
 
            Stream streamFileRead = new FileStream("tttt.txt", FileMode.Open, FileAccess.Read, FileShare.None);
            DataObject data2 = (DataObject)formatter.Deserialize(streamFileRead);
            streamFileRead.Close();
 
            Console.WriteLine("num1 : " + data2.num1);
            Console.WriteLine("num2 : " + data2.num2);
 
        }
    }
}
 
cs


세부 설명
1. 이진 직렬화에 필요한 네임스페이스 선언

1
2
3
using System.IO; // 파일 입출력 스트림을 위해 추가 
using System.Runtime.Serialization.Formatters.Binary; // 바이너리 포맷을 위해 추가 
using System.Runtime.Serialization; // IFormatter 인터페이스 사용을 위해 추가 
cs



2. 직렬화할 클래스(혹은 객체)를 정의

1
2
3
4
5
6
[Serializable] 
public class DataObject 
    public int num1; 
    public int num2; 
cs


꼭 [Serializable]를 붙여야 합니다.

3. 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace ConsoleTest 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            DataObject data1 = new DataObject(); 
            data1.num1 = 1
            data1.num2 = 2
 
 
            IFormatter formatter = new BinaryFormatter(); 
 
            Stream streamFileWrite = new FileStream("tttt.txt", FileMode.Create, FileAccess.Write, FileShare.None); 
            formatter.Serialize(streamFileWrite, data1); 
            streamFileWrite.Close(); 
 
            Stream streamFileRead = new FileStream("tttt.txt", FileMode.Open, FileAccess.Read, FileShare.None); 
            DataObject data2 = (DataObject)formatter.Deserialize(streamFileRead); 
            streamFileRead.Close(); 
 
            Console.WriteLine("num1 : " + data2.num1); 
            Console.WriteLine("num2 : " + data2.num2); 
 
            } 
        } 
cs


Stream streamFileWrite = new FileStream("tttt.txt", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(streamFileWrite, data1);
streamFileWrite.Close();
여기서 data1 객체를 직렬화한 후 tttt.txt에 저장합니다.
파일로 열어보면 다음과 같습니다.


알아볼 수 없도록 이진화로 되어있는 것을 볼 수 있습니다.

그 후 

Stream streamFileRead = new FileStream("tttt.txt", FileMode.Open, FileAccess.Read, FileShare.None);
DataObject data2 = (DataObject)formatter.Deserialize(streamFileRead);
streamFileRead.Close();

이 부분에서 다시 역직렬화합니다.

출력된 데이터를 확인해보면 제대로 데이터가 역직렬화된 것을 알 수 있습니다.

 

 

 

반응형

'개발공부 > C#' 카테고리의 다른 글

[C#] yield  (0) 2019.10.14
[C#] 반복문  (0) 2019.10.13
[C#] 조건문  (0) 2019.10.12
[C#] 연산자  (0) 2019.10.10
[C#] 데이터 타입  (0) 2019.10.09
반응형

 

유니티를 처음 시작하려면 일단 유니티 사이트에 접속합니다.

 

다음 웹페이지로 이동합니다.

 

https://unity.com/kr

 

 

유니티 - Unity

Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.

unity.com

 

유니티 코리아 사이트

웹페이지에 들어간 후 시작하기를 누르면 다음 메뉴가 나오는데,

 

여기서는 입문을 하기위해 다운로드를 받는 것이기 때문에, Personal버전을 받습니다.

 

체크 박스에 체크를 한 후 다운로드 받습니다.

 

여기는 윈도우 버전이므로 Mac OS용은 아래 선택 Mac OS X로 이동하여 다운로드 받습니다.

 

다운로드 받은 UnityHubSetUp.exe를 실행합니다.

 

 

마침 합니다.

 

 

사람 모양을 누른 후 로그인을 합니다.

 

 

아직 계정을 만들지 않았다면, 계정 생성을 합니다.

 

그 후 로그인 합니다.

 

새 라이선스 활성화를 누른 후 

Unity Personal - Unity를 상업적으로 사용하지 않습니다.

 

한 후 완료합니다.

 

닫은 후 시작에서 다시 UnityHub를 엽니다.

 

설치를 누른 후 추가 합니다.

 

최신버전으로 추가합니다.

Unity 2019.3.0a8 선택

다음

 

Dev tools은 Visual Studio 2019를 사용하고, 적용할 플랙폼에 따라서 체크해줍니다.

 

설치를 기다립니다.

 

설치 완료 후 프로젝트 탭으로 이동합니다.

 

새로 생성 버튼을 입력하여 프로젝트를 시작합니다.

 

 

프로젝트 이름을 입력 후 생성 버튼을 누르면 프로젝트가 실행됩니다.

반응형

+ Recent posts