유니티

유니티 XML 저장/불러오기

파란색까마귀 2022. 2. 14. 14:28

2016. 5. 20. 17:13

https://blog.naver.com/nagne2011/220714922406

 

- 24 - Unity - XML 저장/불러오기

먼저 테스트를 위해 확인하기 쉽도록 만들었다 그다음 리스트를 사용하기 위한 using System.Collections...

blog.naver.com

 

먼저 테스트를 위해 확인하기 쉽도록 만들었다

 

그다음

리스트를 사용하기 위한

using System.Collections.Generic;

를 붙여주고

XML을 사용하기 위한

using System.Xml;

도 사용해준다

 

그리고 저장할 항목을 Class로 만들어준다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class saveInfo
{
    public int index;
    public int level;
    public int exp;
    public int currentHeart;
    public int totalHeart;
    public int gold;
    public int npcNumber;
    public int levelBlack;
    public int levelSheep;
    public int levelFishing;
}
cs

 

그다음 위 항목에 맞게

맨위스샷에서 public으로 확인 가능하도록 인게임내 사용할 변수도 생성해준다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
public class xmlTest : MonoBehaviour {
 
    public int index;
    public int level;
    public int exp;
    public int currentHeart;
    public int totalHeart;
    public int gold;
    public int npcNumber;
    public int levelBlack;
    public int levelSheep;
    public int levelFishing;
cs

 

그다음 저장을 해보자

 

 

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
    public static void Write (List<saveInfo> saveList, string path)
    {
        XmlDocument Document = new XmlDocument ();
        //새로운 XML 파일을 생성한다
        XmlElement saveListElement = Document.CreateElement ("saveList");
        //XML요소를 생성해준다 요소의 이름은 "saveList"
        Document.AppendChild (saveListElement);
        //만들어준 요소를 XML파일의 하위로 첨부한다
 
        foreach (saveInfo Save in saveList) 
        {
        //foreach를 사용하여 saveList를 훑어준다
            XmlElement saveElement = Document.CreateElement ("Save");
            //새로운 요소를 생성해준다
            saveElement.SetAttribute ("Index", Save.index.ToString ());
            //생성한 요소의 속성을 만들어준다
            //속성은 (키 이름, 저장할 항목의 값.Tostring()
            //문자열로 저장하기 때문에 int값은 Tostring으로 문자열로 바꾼다
            saveElement.SetAttribute ("level", Save.level.ToString ());
            saveElement.SetAttribute ("exp", Save.exp.ToString ());
            saveElement.SetAttribute ("currentHeart", Save.currentHeart.ToString ());
            saveElement.SetAttribute ("totalHeart", Save.totalHeart.ToString ());
            saveElement.SetAttribute ("gold", Save.gold.ToString ());
            saveElement.SetAttribute ("npcNumber", Save.npcNumber.ToString ());
            saveElement.SetAttribute ("levelBlack", Save.levelBlack.ToString ());
            saveElement.SetAttribute ("levelSheep", Save.levelSheep.ToString ());
            saveElement.SetAttribute ("levelFishing", Save.levelFishing.ToString ());
            saveListElement.AppendChild (saveElement);
            //만들어진 요소를 하위로 첨부한다
        }
        Document.Save (path);
        //파일을 path위치에 저장한다
    }
cs

 

이때 맴버변수로

List와 path를 받는다.

즉, Write(Lsit, path)를 입력하면

해당 List가 path위치에 xml파일로 생성된다

 

다음은 불러오기 방법이다

 

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
public static List<saveInfo> Read(string path)
    {
        XmlDocument Document = new XmlDocument();
        //xml파일을 생성한다
        Document.Load (path);
        //생성한 xml파일에 path에서 가져온 xml을 로드한다
        XmlElement saveListElement = Document ["saveList"];
        //새로운 요소를 생성한다
        List<saveInfo> saveList = new List<saveInfo> ();
        foreach (XmlElement saveElement in saveListElement.ChildNodes) 
        {
        //요소의 하위 항목들을 전부 훑는다
            saveInfo info = new saveInfo ();
            //불러올 항목들을 생성한다
            info.index = System.Convert.ToInt32(saveElement.GetAttribute ("Index"));
            //항목의 index에 불러온 요소중 Index라는 키값을 가진 요소를 집어넣어준다
            //이때, 문자열을 가져왔으니 System.Convert.ToInt32로 int변환 해준다
            info.level = System.Convert.ToInt32(saveElement.GetAttribute ("level"));
            info.exp = System.Convert.ToInt32(saveElement.GetAttribute ("exp"));
            info.currentHeart = System.Convert.ToInt32(saveElement.GetAttribute ("currentHeart"));
            info.totalHeart = System.Convert.ToInt32(saveElement.GetAttribute ("totalHeart"));
            info.gold = System.Convert.ToInt32(saveElement.GetAttribute ("gold"));
            info.npcNumber = System.Convert.ToInt32(saveElement.GetAttribute ("npcNumber"));
            info.levelBlack = System.Convert.ToInt32(saveElement.GetAttribute ("levelBlack"));
            info.levelSheep = System.Convert.ToInt32(saveElement.GetAttribute ("levelSheep"));
            info.levelFishing = System.Convert.ToInt32(saveElement.GetAttribute ("levelFishing"));
            saveList.Add (info);
            //모두 list에 담아준다
        }
        return saveList;
        //불러온 항목이 담긴 list를 return해준다
    }
cs

 

 

확인할 항목을 일단 정해준다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
void Awake()
    {
        index = 0;
        level = 1;
        exp = 0;
        currentHeart = 10;
        totalHeart = 10;
        gold = 1000;
        npcNumber = 0;
        levelBlack = 1;
        levelSheep = 1;
        levelFishing = 1;
    }
cs

 

 

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
57
58
59
60
61
62
63
64
65
66
67
void Update () 
    {
        if (Input.GetKeyDown (KeyCode.Alpha1)) 
        {    
            //값 변화 확인용
            level++;
        }
        if (Input.GetKeyDown (KeyCode.Alpha2)) 
        {
            //값 변화 확인용
            gold++;
        }
        if (Input.GetKeyDown (KeyCode.S)) 
        {
            //저장버튼
            List<saveInfo> saveList = new List<saveInfo> ();
            //저장에 사용할  List를 만든다
            saveInfo info = new saveInfo ();
            //저장할 항목을 가져온다
            info.index = this.index;
            info.level = this.level;
            info.exp = this.exp;
            info.currentHeart = this.currentHeart;
            info.totalHeart = this.totalHeart;
            info.gold = this.gold;
            info.npcNumber = this.npcNumber;
            info.levelBlack = this.levelBlack;
            info.levelSheep = this.levelSheep;
            info.levelFishing = this.levelFishing;
            //현재 값을 항목에 넣어준다
            saveList.Add (info);
            //항목들을 List에 넣는다
            Write (saveList, Application.dataPath + "saveDataList.xml");
            //저장된 값이 들어있는 list를 저장하고, XML파일을 path에 생성한다
            Debug.Log ("Save!!");
            //저장완료!
        }
        if (Input.GetKeyDown (KeyCode.R)) 
        {
            //로드 버튼
            List<saveInfo> saveinfoList = Read (Application.dataPath + "saveDataList.xml");
            //List 생성후 xml파일을 로드해서 담아준다
            for (int i = 0; i < saveinfoList.Count; i++
            {
                //xml파일 내부의 list를 읽어들인다
                saveInfo info = saveinfoList [i];
                //항목을 불러온다
                this.index = info.index;
                this.level = info.level;
                this.exp = info.exp;
                this.currentHeart = info.currentHeart;
                this.totalHeart = info.totalHeart;
                this.gold = info.gold;
                this.npcNumber = info.npcNumber;
                this.levelBlack = info.levelBlack;
                this.levelSheep = info.levelSheep;
                this.levelFishing = info.levelFishing;
                //불러온 항목을 현재 값에 저장한다
            }
            Debug.Log ("Read!!");
            //저장완료!
        }
        if (Input.GetKeyDown (KeyCode.T)) 
        {
            Debug.Log (level + "," + gold);
        }
    }
cs

 

 

이제 테스트를 해보자

 

 

1번과 2번키로 leve과 gold값을 변경한다

1->6

1000->1005



 

S키를 눌러 저장한다

 

 

xml폴더는 path위치에 저장된다



 

요렇게 저장됬다

saveList의 하위 항목에 save요소들로 저장됬다

 

 

 

이제 다시 1,2번 키로 요소를 변경후



 

R버튼을 눌러서 불러오기를 눌러보면

아까 저장했던 대로 불러와서 적용된다




 

728x90

'유니티' 카테고리의 다른 글

유니티 문자열 자르기  (0) 2022.02.14
유니티 파일/폴더 생성, 삭제, 확인  (0) 2022.02.14
유니티 터치좌표로 상하좌우 구분하기  (0) 2022.02.14
유니티 버튼만들기  (0) 2022.02.13
유니티 스카이맵  (0) 2022.02.13