본문 바로가기
게임 개발/Unity3D

[Unity | 유니티] 구글플레이 연동을 위한 GooglePlayMgr 스크립트 작성하기

by 불타는홍당무 2017. 6. 13.



유니티 프로젝트와 구글플레이 서비스 연동하기

https://www.youtube.com/watch?v=BhSJK-Kn8Uw&t=3s


구글플레이를 연동 스크립트를 작성했다. 당연히 싱글톤 패턴으로 구현했고, 공식사이트에 있는 예제를 참고했다. 초기화, 로그인, 로그아웃, 업적 조회, 리더보드 조회와 같은 기본 기능만 구현했고, 업적 달성과 같은 기능은 조만간 추가할 예정이다.


using UnityEngine;
using GooglePlayGames;
using System.Collections.Generic;

public class GooglePlayGamesMgr
{
    //싱글톤 패턴
    private static GooglePlayGamesMgr _instance;
    public static GooglePlayGamesMgr Instance
    {
        get
        {
            if (_instance == null) _instance = new GooglePlayGamesMgr();
            return _instance;
        }
    }

    private bool _authenticating = false;
    public bool Authenticated { get { return Social.Active.localUser.authenticated;  } }

    //list of achievements we know we have unlocked (to avoid making repeated calls to the API)
    private Dictionary<string, bool> _unlockedAchievements = new Dictionary<string, bool>();

    //achievement increments we are accumulating locally, waiting to send to the games API
    private Dictionary<string, int> _pendingIncrements = new Dictionary<string, int>();

    //GooglePlayGames 초기화
    public void Initialize()
    {
        //PlayGamesPlatform 로그 활성화/비활성화
        PlayGamesPlatform.DebugLogEnabled = false;
        //Social.Active 초기화
        PlayGamesPlatform.Activate();
    }

    //GooglePlayGames 로그인
    public void SignInToGooglePlay()
    {
        if (Authenticated || _authenticating)
        {
            Debug.LogWarning("Ignoring repeated call to Authenticate().");
            return;
        }

        _authenticating = true;
        Social.localUser.Authenticate((bool success) =>
        {
            _authenticating = false;
            if (success)
            {
                Debug.Log("Sign in successful!");
            }
            else
            {
                Debug.LogWarning("Failed to sign in with Google Play");
            }
        });
    }

    //GooglePlayGames 로그아웃
    public void SignOutFromGooglePlay()
    {
        GooglePlayGames.PlayGamesPlatform.Instance.SignOut();
    }

    //업적 조회하기
    public void ShowGooglePlayAchievements()
    {
        if (Authenticated)
        {
            Social.ShowAchievementsUI();
        }
    }

    //리더보드 조회하기
    public void ShowLeaderboardUI()
    {
        if (Authenticated)
        {
            Social.ShowLeaderboardUI();
        }
    }
}