GPGS 클라우드 저장/불러오기

Unity3D 2018. 12. 3. 15:45
반응형

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames.BasicApi; //conf
using GooglePlayGames;  //platfom
using GooglePlayGames.BasicApi.SavedGame;
using System;
using System.Text;
using Newtonsoft.Json;
using System.IO;
 
public class GPGSManager : MonoBehaviour {
 
    //2018.12.03 [GPGS 클라우드]
    public Action<SavedGameRequestStatus, byte[]> OnSavedGameDataReadComplete;
    public Action<SavedGameRequestStatus, ISavedGameMetadata> OnSavedGameDataWrittenComplete;
    private bool isSaving;
    private const string FILE_NAME = "AppSmilejsuGameInfo.bin";
 
 
    //초기화 
    public void Init()
    {
        PlayGamesClientConfiguration conf = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
        PlayGamesPlatform.InitializeInstance(conf);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
    }
 
 
    //로그인 
    public void SignIn(System.Action<bool> onComplete)
    {
        Social.localUser.Authenticate(onComplete);
    }
 
    #region 저장
    public void SaveData()
    {
        if (Social.localUser.authenticated)
        {
            this.isSaving = true;
            ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
            savedGameClient.OpenWithAutomaticConflictResolution(FILE_NAME, DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, OnSavedGameOpened);
        }
        else
        {
            this.SaveLocal();
        }
    }
 
    private void SaveLocal()
    {
        var path = Application.persistentDataPath + "/AppSmilejsuGameInfo.bin";
        var json = JsonConvert.SerializeObject(App.Instance.gameInfo);
        byte[] bytes = Encoding.UTF8.GetBytes(json);
        File.WriteAllBytes(path, bytes);
    }
 
    private void SaveGame(ISavedGameMetadata data)
    {
        this.SaveLocal();
 
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
        var stringToSave = this.GameInfoToString();
        byte[] bytes = Encoding.UTF8.GetBytes(stringToSave);
        savedGameClient.CommitUpdate(data, update, bytes, OnSavedGameDataWrittenComplete);
        
    }
 
    #endregion
 
    #region 불러오기 
    public void LoadData()
    {
        if (Social.localUser.authenticated)
        {
            this.isSaving = false;
            ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(FILE_NAME, DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, this.OnSavedGameOpened);
        }
        else
        {
            this.LoadLocal();
        }
    }
 
    private void LoadLocal()
    {
        var path = Application.persistentDataPath + "/AppSmilejsuGameInfo.bin";
        byte[] bytes = File.ReadAllBytes(path);
        var json = Encoding.UTF8.GetString(bytes);
 
        this.StringToGameInfo(json);
    }
 
    private void LoadGame(ISavedGameMetadata data)
    {
        ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(data, OnSavedGameDataReadComplete);
    }
    #endregion
 
    private void OnSavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game)
    {
        Debug.LogFormat("OnSavedGameOpened : {0}, {1}", status, isSaving);
 
        if (status == SavedGameRequestStatus.Success)
        {
            if (!isSaving)
            {
                this.LoadGame(game);
            }
            else
            {
                this.SaveGame(game);
            }
        }
        else
        {
            if (!isSaving)
            {
                this.LoadLocal();
            }
            else
            {
                this.SaveLocal();
            }
        }
    }
 
    public void StringToGameInfo(string localData)
    {
        if (localData != string.Empty)
        {
            App.Instance.gameInfo = JsonConvert.DeserializeObject<GameInfo>(localData);
        }
    }
 
    private string GameInfoToString()
    {
        return JsonConvert.SerializeObject(App.Instance.gameInfo);
    }
 
 
}
 
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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GooglePlayGames;
using System;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using GooglePlayGames.BasicApi.SavedGame;
 
public class App : MonoBehaviour
{
    //2018.11.29 [업적]
    public Text txtUserName;        //유저 이름 
    public GameObject uiTitleGo;       //타이틀 UI 오브젝트 
    public GameObject uiInGameGo;   //인게임 UI 오브젝트 
    public Button btnGameStart;     //게임 시작 버튼 
    public Button btnKillNormalMonster; //일반 몬스터 처치 버튼
    public Button btnKillEliteMonster;  //정예몬스터 처치 버튼 
    public Button btnAchievement;   //업적 버튼 
    public Text txtNormalMonsterKillCount;  //일반 몬스터 처치 텍스트 
    public Text txtEliteMonsterKillCount;   //정예 몬스터 처치 텍스트 
    public GPGSManager gpgsManager;
    //private int killNormalMonsterCount; //일반몬스터 처치 수 
    //private int killEliteMonsterCount;  //정예몬스터 처치 수 
 
 
    //2018.11.30 [리더보드]
    public Text txtHighScore;       //최대점수 텍스트 
    public Text txtScore;           //텍스트 점스 
    public Button btnLeaderboard;   //리더보드 버튼 
    //private int highScore;          //최대점수 
    private int score;              //점수 
    //private const string HIGH_SCORE = "HIGH_SCORE"; //상수 (PlayerPrebs의 키)
    public GameObject mode00Go;     //일반 모드 
    public GameObject mode01Go;     //보스 타임 어택 모드 
    public Button btnBossTimeAttack;        //보스 타임어택 버튼 
    public Button btnAttackBoss;        //보스 공격 버튼 
    public Button btnBack;  //되돌아가기 버튼 
    public Text txtRemainTime;      //남은 시간 
    public Text txtBossHp;      //보스 체력 
    public Text txtDamage;      //공격력 
    public Text txtBossTimeAttackResult;    //보스타임어택 결과 텍스트 
    private bool isBossTimeAttack;  //보스타임어택인지 아닌지?
    private int bossHp;     //보스 체력 
    private int damage;     //공격력 
    private DateTime dtStart;   //시작 시간 
    private DateTime dtLimit;   //제한 시간 
    private TimeSpan tsRemainTime;  //남은 시간 
    private TimeSpan tsElapsedTime;     //경과 시간 
    public Button btnLeaderboardBossTimeAttack;
 
 
    //2018.12.03 [클라우드]
    public static App Instance;
    public GameInfo gameInfo;
    public Button btnSave;
    public Button btnLoad;
    public Text txtBossKillCount;
    public Text txtCloudResult;
 
    private void Awake()
    {
        //PlayerPrefs.DeleteAll();
        App.Instance = this;
    }
 
 
    // Use this for initialization
    void Start()
    {
        this.gpgsManager.OnSavedGameDataReadComplete = (status, bytes) => {
            if (status == SavedGameRequestStatus.Success)
            {
                string strCloudData = null;
 
                if (bytes.Length == 0)
                {
                    strCloudData = string.Empty;
                    txtCloudResult.text = "로드 성공, 데이터 없음";
                }
                else
                {
                    strCloudData = Encoding.UTF8.GetString(bytes);
                    this.gameInfo = JsonConvert.DeserializeObject<GameInfo>(strCloudData);
                    this.txtNormalMonsterKillCount.text = this.gameInfo.normalMonsterKillCount.ToString();
                    this.txtEliteMonsterKillCount.text = this.gameInfo.eliteMonsterKillCount.ToString();
                    this.txtBossKillCount.text = this.gameInfo.killBossCount.ToString();
                    this.txtHighScore.text = this.gameInfo.highScore.ToString();
                    this.txtScore.text = this.score.ToString();
                    txtCloudResult.text = "클라우드로부터 데이터를 불러왔습니다.";
                }
            }
            else {
                txtCloudResult.text = string.Format("로드 실패 : {0}", status);
            }
        };
 
        this.gpgsManager.OnSavedGameDataWrittenComplete = (status, game) => {
            if (status == SavedGameRequestStatus.Success)
            {
                txtCloudResult.text = "클라우드에 저장 하였습니다.";
            }
        };
 
        this.gpgsManager.Init();
 
        this.gpgsManager.SignIn((result) =>
        {
            //result = true;
 
            if (result)
            {
                this.txtUserName.text = Social.localUser.userName;
 
                //로그인성공
                //타이틀 보여주기 
                this.uiTitleGo.SetActive(true);
 
                this.Init();
            }
            else
            {
                Debug.Log("로그인 실패");
                this.txtUserName.text = "로그인 실패";
                
                //타이틀 보여주기 
                this.uiTitleGo.SetActive(true);
 
                this.Init();
            }
 
        });
 
        //시작 버튼 이벤트 등록 
        this.btnGameStart.onClick.AddListener(() =>
        {
 
            //업적 달성 (게임의 시작)
            Social.ReportProgress(GPGSIds.achievement, 100.0f, (result) =>
            {
                Debug.LogFormat("업적 달성 (게임의 시작) : {0}", result);
            });
 
            //인게임으로 넘어감 
            this.uiTitleGo.SetActive(false);
            this.uiInGameGo.SetActive(true);
 
        });
 
        //일반 몬스터 처치 버튼 이벤트 등록 
        this.btnKillNormalMonster.onClick.AddListener(() =>
        {
            this.gameInfo.normalMonsterKillCount += 1;
            
            Debug.LogFormat("일반몬스터 처치수: {0}"this.gameInfo.normalMonsterKillCount);
            this.txtNormalMonsterKillCount.text = this.gameInfo.normalMonsterKillCount.ToString();
 
            if (this.gameInfo.normalMonsterKillCount == 10)
            {
                Social.ReportProgress(GPGSIds.achievement___10, 100.0f, (result) =>
                {
                    Debug.LogFormat("업적 달성 (일반몬스터 10마리처치) : {0}", result);
                });
 
                PlayGamesPlatform.Instance.IncrementAchievement(GPGSIds.achievement_2, 1, (result) =>
                {
 
                    var ach = PlayGamesPlatform.Instance.GetAchievement(GPGSIds.achievement_2);
                    //1/2
                    //Debug.LogFormat("업적 달성 (몬스터 헌터) : {0}, {1}/{2}", result, ach.CurrentSteps, ach.TotalSteps);
 
                });
            }
 
            this.UpdateScore(1);
 
        });
 
        //정예 몬스터 처치 버튼 이벤트 등록 
        this.btnKillEliteMonster.onClick.AddListener(() =>
        {
            this.gameInfo.eliteMonsterKillCount += 1;
            Debug.LogFormat("정예몬스터 처치수: {0}"this.gameInfo.eliteMonsterKillCount);
            this.txtEliteMonsterKillCount.text = this.gameInfo.eliteMonsterKillCount.ToString();
            if (this.gameInfo.eliteMonsterKillCount == 2)
            {
                Social.ReportProgress(GPGSIds.achievement___2, 100.0f, (result) =>
                {
                    Debug.LogFormat("업적 달성 (정예몬스터 2마리 처치) : {0}", result);
                });
 
                PlayGamesPlatform.Instance.IncrementAchievement(GPGSIds.achievement_2, 1, (result) =>
                {
                    var ach = PlayGamesPlatform.Instance.GetAchievement(GPGSIds.achievement_2);
 
                    //Debug.LogFormat("업적 달성 (몬스터 헌터) : {0}, {1}/{2}", result, ach.CurrentSteps, ach.TotalSteps);
                });
            }
 
            this.UpdateScore(2);
        });
 
        //업적 버튼 이벤트 등록 
        this.btnAchievement.onClick.AddListener(() =>
        {
            //업적 UI보여주기 
            Debug.Log("업적 UI보여주기 ");
 
            Social.ShowAchievementsUI();
        });
 
        //리더보드 버튼 이벤트 등록 
        this.btnLeaderboard.onClick.AddListener(() => {
 
            //리더보드 UI보여주기 
            Social.ShowLeaderboardUI();
        });
 
        //보스타임어택 버튼 이벤트 등록 
        this.btnBossTimeAttack.onClick.AddListener(() => {
            this.StartBossTimeAttack();
        });
 
        //보스 공격 버튼 이벤트 등록 
        this.btnAttackBoss.onClick.AddListener(() => {
            //보스 공격 하기 
            this.AttackBoss();
        });
 
        //백버튼 이벤트 등록 
        this.btnBack.onClick.AddListener(() => {
            this.isBossTimeAttack = false;
            this.mode01Go.SetActive(false);
            this.mode00Go.SetActive(true);
        });
 
        //보스타임어택 리더보드 UI
        this.btnLeaderboardBossTimeAttack.onClick.AddListener(() => {
            PlayGamesPlatform.Instance.ShowLeaderboardUI(GPGSIds.leaderboard_2);
        });
 
        this.btnSave.onClick.AddListener(() => {
 
            this.gpgsManager.SaveData();
 
        });
        this.btnLoad.onClick.AddListener(() => {
 
            this.gpgsManager.LoadData();
 
        });
 
    }
 
    private void StartBossTimeAttack()
    {
        //모드 00 비활성화 
        this.mode00Go.SetActive(false);
        //모드 01 활성화 
        this.mode01Go.SetActive(true);
       
        //보스타임어택 시작 
        this.isBossTimeAttack = true;
 
        //초기화 해야 하는것들 (남은시간 , 보스 체력, 데미지)
        this.dtStart = DateTime.Now;
        this.dtLimit = DateTime.Now.AddSeconds(5);     //1분 30초 
        this.tsRemainTime = this.dtLimit - DateTime.Now;
        this.bossHp = 100;
        this.damage = 10;
 
        this.txtRemainTime.text = string.Format("{0}분 {1:00}초"this.tsRemainTime.Minutes, this.tsRemainTime.Seconds);
        this.txtBossHp.text = this.bossHp.ToString();
        this.txtDamage.text = this.damage.ToString();
 
        //결과는 비활성화 
        this.txtBossTimeAttackResult.gameObject.SetActive(false);
 
        //버튼은 활성화 
        this.btnAttackBoss.gameObject.SetActive(true);
            
    }
 
    private void EndBossTimeAttack(bool isSuccess)
    {
        //결과를 보여주기 
        if (isSuccess)
        {
            this.txtBossTimeAttackResult.text = string.Format("{0}초만에 보스를 쓰러트렸습니다. ", tsElapsedTime.TotalSeconds);
 
            Social.ReportScore((long)tsElapsedTime.TotalMilliseconds, GPGSIds.leaderboard_2, (result) => {
                Debug.LogFormat("결과  : {0}, {1}", (long)tsElapsedTime.TotalMilliseconds, result);
            });
 
            this.gameInfo.killBossCount++;
            this.txtBossKillCount.text = this.gameInfo.killBossCount.ToString();
            
 
            this.gameInfo.lastSavedTime = DateTime.Now.ToString();
            this.gpgsManager.SaveData();
        }
        else
        {
            this.txtBossTimeAttackResult.text = "타임오버";
        }
 
        this.txtBossTimeAttackResult.gameObject.SetActive(true);
        this.btnAttackBoss.gameObject.SetActive(false);
    }
 
    private void AttackBoss()
    {
        this.bossHp -= this.damage;
        if (this.bossHp <= 0)
        {
            this.bossHp = 0;
            this.isBossTimeAttack = false;
            this.EndBossTimeAttack(true);
        }
 
        this.txtBossHp.text = this.bossHp.ToString();
    }
 
 
 
    void Update()
    {
        if (this.isBossTimeAttack)
        {
            //경과 시간 계산하기 
            this.tsElapsedTime =  DateTime.Now - this.dtStart;
 
            Debug.LogFormat("{0}초"this.tsElapsedTime.TotalSeconds);
 
            //남은 시간 계산 하기 
            //시간계산 하고 보여주기 
            this.tsRemainTime = this.dtLimit - DateTime.Now;
            this.txtRemainTime.text = string.Format("{0}분 {1:00}초"this.tsRemainTime.Minutes, this.tsRemainTime.Seconds);
 
 
            if (this.tsRemainTime.TotalSeconds <= 0)
            {
                //타임 오버 
                this.isBossTimeAttack = false;
 
                this.EndBossTimeAttack(false);
            }
        }
    }
 
    private void Init()
    {
        
        //모드 00 활성화 
        this.mode00Go.SetActive(true);
        //모드 01 비활성화 
        this.mode01Go.SetActive(false);
 
        var path = Application.persistentDataPath + "/AppSmilejsuGameInfo.bin";
 
        Debug.Log(path);
 
        Debug.LogFormat("Exists: {0}"File.Exists(path));
 
        if (File.Exists(path))
        {
            this.gpgsManager.LoadData();
        }
        else
        {
            this.gameInfo = new GameInfo();
            this.gameInfo.userId = Social.localUser.id;
            this.gameInfo.lastSavedTime = DateTime.Now.ToString();
 
            this.txtNormalMonsterKillCount.text = this.gameInfo.normalMonsterKillCount.ToString();
            this.txtEliteMonsterKillCount.text = this.gameInfo.eliteMonsterKillCount.ToString();
            this.txtBossKillCount.text = this.gameInfo.killBossCount.ToString();
            this.txtHighScore.text = this.gameInfo.highScore.ToString();
            this.txtScore.text = this.score.ToString();
 
 
            var json = JsonConvert.SerializeObject(this.gameInfo);
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            File.WriteAllBytes(path, bytes);
 
            //PlayerPrefs.SetString(FILE_NAME, JsonConvert.SerializeObject(App.Instance.gameInfo));
        }
 
    }
 
    //점수를 업데이트 합니다.
    private void UpdateScore(int score)
    {
        //점수 증가 및 표시 
        this.score += score;
        this.txtScore.text = this.score.ToString();
 
        //최대점수 도달시 최대점수 표시 및 갱신 
        if (this.gameInfo.highScore < this.score)
        {
            this.gameInfo.highScore = this.score;
            //PlayerPrefs.SetInt(HIGH_SCORE, this.highScore);
            this.txtHighScore.text = this.gameInfo.highScore.ToString();
 
            //리더보드 업데이트 
            Social.ReportScore(this.gameInfo.highScore, GPGSIds.leaderboard, (result) => {
                Debug.LogFormat("ReportScore : {0}, {1}"this.gameInfo.highScore, result);
            });
        }
    }
 
}
 
cs


반응형

'Unity3D' 카테고리의 다른 글

Unity에서 .NET 4.x 사용  (0) 2018.12.27
socket.io with unity  (1) 2018.12.24
GPGS 리더보드  (0) 2018.11.29
GPGS 업적  (0) 2018.11.28
GPGS 로그인  (0) 2018.11.27
: