블로그 이미지
래머
오늘도 열심히 개발하는 개발자입니다.

calendar

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

Notice

2015. 10. 30. 09:50 Unity
구글플레이 서비스에서 유용한점 하나가 클라우드 저장기능입니다.

서버가 없는 게임인경우 게임데이터를 구글클라우드 서버에 저장하거나 가져오기를 통해서 사용자의 데이터를 안전하게 보관할 수 있습니다.


아래 주소에서 유니티용 플러그인을 다운로드 할 수 있습니다.

https://github.com/playgameservices/play-games-plugin-for-unity


구글플레이 게임서비스 이용에 관한 전반적인 사항은 검색을 통해서 확인하시기 바랍니다.


클라우드 저장기능사용에 대한 핵심적인 부분만 코드로 보여드립니다.

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
 
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.SavedGame;
 
public static class CGoogleplayGameServiceManager
{
    //게임서비스 플러그인 초기화시에 EnableSavedGames()를 넣어서 저장된 게임 사용할 수 있게 합니다.
    //주의 하실점은 구글플레이 개발자 콘솔의 게임서비스에서 해당게임의 세부정보에서 저장된 게임 사용을 
    //하도록 설정하셔야 합니다.
    public static void Init()
    {
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
 
        PlayGamesPlatform.InitializeInstance(config);
 
        //
        PlayGamesPlatform.DebugLogEnabled = false;
 
        //Activate the Google Play gaems platform
 
        PlayGamesPlatform.Activate();
    }
 
    //인증여부 확인
    public static bool CheckLogin()
    {
        return Social.localUser.authenticated;
    }
    //--------------------------------------------------------------------
    //게임 저장은 다음과 같이 합니다.
    public static void SaveToCloud()
    {
        if (!CheckLogin()) //로그인되지 않았으면
        {
            //로그인루틴을 진행하던지 합니다.
            return;
        }
 
        //파일이름에 적당히 사용하실 파일이름을 지정해줍니다.
        OpenSavedGame("사용할파일이름"true);
    }
 
    static void OpenSavedGame(string filename, bool bSave)
    {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
 
        if (bSave)
            savedGameClient.OpenWithAutomaticConflictResolution(filename, DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, OnSavedGameOpenedToSave); //저장루틴진행
        else
            savedGameClient.OpenWithAutomaticConflictResolution(filename, DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, OnSavedGameOpenedToRead); //로딩루틴 진행
    }
 
 
    //savedGameClient.OpenWithAutomaticConflictResolution호출시 아래 함수를 콜백으로 지정했습니다. 준비된경우 자동으로 호출될겁니다.
        static void OnSavedGameOpenedToSave(SavedGameRequestStatus status, ISavedGameMetadata game)
        {
            if (status == SavedGameRequestStatus.Success)
        {
            // handle reading or writing of saved game.
 
                //파일이 준비되었습니다. 실제 게임 저장을 수행합니다.
                //저장할데이터바이트배열에 저장하실 데이터의 바이트 배열을 지정합니다.
                SaveGame(game, "저장할데이터바이트배열", DateTime.Now.TimeOfDay);
        }
        else
        {
            //파일열기에 실패 했습니다. 오류메시지를 출력하든지 합니다.
        }
    }
 
    static void SaveGame(ISavedGameMetadata game, byte[] savedData, TimeSpan totalPlaytime)
    {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
 
        SavedGameMetadataUpdate.Builder builder = new SavedGameMetadataUpdate.Builder();
        builder = builder
            .WithUpdatedPlayedTime(totalPlaytime)
            .WithUpdatedDescription("Saved game at " + DateTime.Now);
 
        /*
        if (savedImage != null)
        {
            // This assumes that savedImage is an instance of Texture2D
            // and that you have already called a function equivalent to
            // getScreenshot() to set savedImage
            // NOTE: see sample definition of getScreenshot() method below
            byte[] pngData = savedImage.EncodeToPNG();
            builder = builder.WithUpdatedPngCoverImage(pngData);
        }*/
 
        SavedGameMetadataUpdate updatedMetadata = builder.Build();
        savedGameClient.CommitUpdate(game, updatedMetadata, savedData, OnSavedGameWritten);
    }
 
    static void OnSavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game)
    {
        ShowActionBar(falsetrue);
 
        if (status == SavedGameRequestStatus.Success)
        {
            //데이터 저장이 완료되었습니다.
        }
        else
        {
            //데이터 저장에 실패 했습니다.
        }
    }
 
    //----------------------------------------------------------------------------------------------------------------
    //클라우드로 부터 파일읽기
    public static void LoadFromCloud()
    {
        if (!CheckLogin())
        {
            //로그인되지 않았으니 로그인 루틴을 진행하던지 합니다.
            return;
        }
 
        //내가 사용할 파일이름을 지정해줍니다. 그냥 컴퓨터상의 파일과 똑같다 생각하시면됩니다.
        OpenSavedGame("사용할파일이름"false);
    }
 
 
    static void OnSavedGameOpenedToRead(SavedGameRequestStatus status, ISavedGameMetadata game)
    {
        if (status == SavedGameRequestStatus.Success)
        {
            // handle reading or writing of saved game.
            LoadGameData(game);
        }
        else
        {
            //파일열기에 실패 한경우, 오류메시지를 출력하던지 합니다.
        }
    }
 
    //데이터 읽기를 시도합니다.
    static void LoadGameData(ISavedGameMetadata game)
    {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        savedGameClient.ReadBinaryData(game, OnSavedGameDataRead);
    }
 
    static void OnSavedGameDataRead(SavedGameRequestStatus status, byte[] data)
    {
            if (status == SavedGameRequestStatus.Success)
            {
                // handle processing the byte array data
 
                //데이터 읽기에 성공했습니다.
                //data 배열을 복구해서 적절하게 사용하시면됩니다.
            }
            else
            {
                //읽기에 실패 했습니다. 오류메시지를 출력하던지 합니다.
            }
    }
}
cs


'Unity' 카테고리의 다른 글

유니티 텍스쳐 직접조작  (0) 2017.02.14
유니티 Editor 폴더내에 있는 Resources폴더  (0) 2017.01.29
블록 게임  (0) 2015.08.22
빌보드 테스트  (0) 2015.08.16
유니티 애즈(Unity Ads) 동영상 광고 사용해 보기  (2) 2015.07.12
posted by 래머